【python】numpy基础操作|代码示例
·
参考
https://www.runoob.com/numpy/numpy-tutorial.html
【【莫烦Python】Numpy & Pandas (数据处理教程)】 https://www.bilibili.com/video/BV1Ex411L7oT/?share_source=copy_web&vd_source=9332b8fc5ea8d349a54c3989f6189fd3
创建数组、改变形状、基础运算
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
# print(a)
# print(a.ndim)
# print(a.shape)
# print(a.size)
# 2
# (2, 3)
# 6
b = np.zeros(6)
print(b)
c = b.reshape(2, 3)
print(c)
d = np.ones((3, 4))
print(d)
f = a.reshape(3, 2)
# [0. 0. 0. 0. 0. 0.]
# [[0. 0. 0.]
# [0. 0. 0.]]
# [[1. 1. 1. 1.]
# [1. 1. 1. 1.]
# [1. 1. 1. 1.]]
e = np.arange(1, 10, 2) # [1 3 5 7 9]
print(e)
print(np.max(a))
print(np.sum(a)) # 21
print('axis0:', np.sum(a, axis=0)) # [5 7 9],按列,3列
print('axis1', np.sum(a, axis=1)) # [ 6 15]
print(np.max(a, axis=0))
print('max index:', np.argmax(a)) # 求索引
print(np.argmax(a, axis=0)) # 求索引
print(a.mean())
print(np.median(a))
print(a.cumsum()) # [ 1 3 6 10 15 21],依次累加
print(a.min())
# 矩阵乘法
print(a.dot(f))
print(np.random.random((2, 4))) # 随机生成0到1的数
t = np.array([[1, 2, 3, 4]])
print(t.min(axis=0)) # [1 2 3 4]
x = a.transpose((1, 0)) # transpose调整数组的维度顺序
print(x)
# [[1 4]
# [2 5]
# [3 6]]
y = a.clip(min=4, max=5) # 截断,超出范围的按某个值算
print(y)
xx = np.arange(24).reshape((3, 4, 2))
print(xx.transpose(2,1,0))
索引、切片、分割
import copy
import numpy as np
# 按索引来访问
a = np.arange(2, 14).reshape(3, 4)
print(a[1])
print(a[1][1])
print(a[1, 1])
print(a[1, ::-1]) # 可以选某个维度进行切片
# [6 7 8 9]
# 7
# 7
# 9
# 展平
f = a.flatten()
print(f)
for it in f:
print(it)
# 乘号是对应位置逐元素分别相乘
b = np.array([[1, 2, 3], [4, 5, 6]], dtype=np.int32)
c = copy.copy(b)
print(b * c)
# print(np.split(b, 2, axis=1)) # 只能均分,ValueError: array split does not result in an equal division
print(np.split(b, 3, axis=1))
更多推荐

所有评论(0)