numpy
参考资料:https://github.com/kailashahirwar/cheatsheets-ai/blob/master/Numpy.png
Numpy是Python的一种开源的数值计算扩展,可用来存储和处理大型矩阵
import numpy as np
创建数组
a = np.array([1, 2, 3]) # shape (3,)
b = np.array([(1.5, 2, 3), (4, 5, 6)], dtype=float) # shape(2, 3)
c = np.array([[(1.5, 2, 3), (4, 5, 6)], [(3, 2, 1), (6, 5, 4)]], dtype=float) # shape(2, 2, 3)
np.zeros((3, 4)) # 创建为0的数组
np.ones((2, 3, 4), dtype=np.int16) # 创建全为1的数组
d = np.arange(10, 30, 5) # 创建10到30之间的数组,步长为5
np.linspace(0, 2, 9) # 均匀的产生0到2之间的9个数字
e = np.full((2, 2), 7) # 创建2行2列的常数为7的数组
f = np.eye(2) # 创建2*2的单位矩阵
np.random.random((2, 2)) # 创建2*2的随机矩阵
np.empty((3, 2)) # 创建空矩阵
保存数组
np.save('my_array', a) # 保存数组到当前文件目录的my_array.npy
np.savez('array.npz', a, b)
np.load('my_array.npy')
np.load('array.npz')
常见的numpy数据类型
np.int64 # 64位整型数据
np.float32 # 标准的双精度浮点型数据
np.complex # 复数型数据
np.bool # 布尔型数据,True或者False
np.object # python对象
np.string_ # 固定长度的字符数据
np.unicode_ # 固定长度的unicode类型
数组的属性获取
a.shape # 数组的维度
len(a) # 数组的长度
b.ndim # 数组有多少个维度
a.size # 数组中元素的个数
b.dtype # 数组的类型
b.dtype.name # 类型的名称
f = b.astype(int) # 类型转换
f.dtype # dtype('int64')
数组之间的数学计算
g = a - b
np.subtract(a, b) # np的减法操作
a + b
np.add(a, b) # np的加法操作
a / b
np.divide(a, b) # np的除法操作
np.multiply(a, b) # 乘法操作
np.exp(b) # 取指数操作
np.sqrt(b) # 开根号
np.sin(a)
np.cos(b)
np.log(a)
a = np.array([[1, 2], [3, 3]])
b = np.array([[2, 9], [3, 4]])
a.dot(b) # 点乘操作 [[8,17], [15, 39]]
np.multiply(a, b) # 乘法操作 [[2, 18], [9, 12]]
a == b # [[False, False], [True, False]]
a < 3 # [[True, True], [False, False]]
常用函数
a.sum() # 求和
a.min() # 求最小值
b.max(axis=0) # 按列求最大值
b.cumsum(axis=1) # 按元素依次求和--行
a.mean() # 计算a的均值
np.std(b) # 计算标准差
np.transpose(b) # b的转置函数
g = b.ravel() # 平铺整个数组
g.reshape(3, 2)
复制数组
h = a.view()
np.copy(a)
h = a.copy()
fancy index获取数组元素
fancy indexing:即指传递索引数组以便一次得到多个数组元素
b = np.array([[1, 2, 3], [4, 5, 6]])
b[1, 1] # 5
b[b<5] # [1 2 3 4]
b[[1, 0, 1, 0], [0, 1, 2, 0]] # [4 2 6 1]
b[[1, 0, 1, 0]][:, [0, 1, 2, 0]] # [[4, 5, 6, 4], [1, 2, 3, 1], [4, 5, 6, 4], [1, 2, 3, 1]]
数组合并,以及插入值
a = np.array([2, 3, 4])
d = np.arange(10, 21, 5) # [10 15 20]
np.insert(a, 1, 5) # [2 5 3 4 10 15 20]
np.append(a, d) # [2 3 4 10 15 20]
np.delete(a, [1]) # [2 4]
np.concatenate((a, d), axis=0) # [[2 3 4], [1 2 3], [4 5 6]]
np.vstack((a, d)) # 合并两个数组,按行合并 [[2 3 4], [10 15 20]]
np.r_[e, f]
np.column_stack((a, d)) # 按列合并两个数组 [[2 10], [3 15], [4 20]]
数组切分
np.hsplit(a, 3) # 纵向切分数据 [array([2]), array([3]), array([4])]
np.vsplit(b, 2) # 横向切分数据 [array([[1, 2, 3]]), array([[4, 5, 6]])]