前言
numpy是python一个库,无论是数据分析还是视觉算法,甚至一些脚本运算都需要运用到numpy库。99%的人学了忘,忘了学,本文针对numpy常用的方法做了一些总结。觉得有用记得收藏,以免下次找不到。
1、numpy数组初始化
代码语言:javascript复制import numpy as np
a = np.array([1, 2, 3])
b = np.arange(1, 10)
c = np.eye(3) # 单位矩阵
d = np.zeros((3, 3)) # 构建3*3 全0矩阵
e = np.ones([3, 3]) # 构建3*3 全1矩阵 [3,3]与(3,3)都可
data = np.loadtxt("test.txt", delimiter=",") # 加载txt文件数据
2、数组处理
代码语言:javascript复制import numpy as np
a = np.arange(1, 10)
b = a.reshape(3, 3) # 改变size
print(b)
[[1 2 3]
[4 5 6]
[7 8 9]]
c = np.ravel(b) # 平铺为一维向量
[1 2 3 4 5 6 7 8 9]
print(b[:, 0:1])
[[1]
[4]
[7]]
print(b[:, (0, 2)]) # 切片获取
[[1 3]
[4 6]
[7 9]]
e = np.arange(9, 18).reshape(3, 3)
print(b, "n", e)
b = [[1 2 3]
[4 5 6]
[7 8 9]]
e = [[ 9 10 11]
[12 13 14]
[15 16 17]]
print(np.vstack([b, e])) # 竖着拼接
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[ 9 10 11]
[12 13 14]
[15 16 17]]
print(np.hstack([b, e])) # 横着拼接
[[ 1 2 3 9 10 11]
[ 4 5 6 12 13 14]
[ 7 8 9 15 16 17]]
s = np.array([0.0, 1.0, 2.0, 3.0])
print(np.broadcast_to(s[:, np.newaxis], (4, 2)))
[[0. 0.]
[1. 1.]
[2. 2.]
[3. 3.]]
print(np.broadcast_to(s[np.newaxis:, ], (2, 4)))
[[0. 1. 2. 3.]
[0. 1. 2. 3.]]
3、线性代数
代码语言:javascript复制import numpy as np
# 矩阵乘积
a = np.arange(1, 5).reshape(2, 2)
b = np.arange(5, 9).reshape(2, 2)
print("a:", a, "n", "b:", b)
a: [[1 2]
[3 4]]
b: [[5 6]
[7 8]]
print(np.dot(a, b))
print(np.matmul(a, b))
print(a @ b)
# np.dot、np.matmul,@返回结果都一样 选择一种方法记住就行
[[19 22]
[43 50]]
print(a * b)
[[ 5 12]
[21 32]]
代码语言:javascript复制# 矩阵转置
a = np.arange(1, 5).reshape(2, 2)
a = [[1 2]
[3 4]]
print(a.T)
[[1 3]
[2 4]]
print(np.transpose(a))
[[1 3]
[2 4]]
# 矩阵特征计算
np.linalg.inv(a) # 矩阵的逆
np.trace(a) # 矩阵的迹
np.linalg.det(a) # 方阵行列式的值
# 1x 2y = 3
# 3x 4y = 5
solve = np.linalg.solve(a, np.array([3, 5])) # 解线性方程组
print(solve)
[-1. 2.]
4、数学函数
代码语言:javascript复制import numpy as np
# 三角函数
print(np.pi) # π = 3.141592653589793
print(np.e) # e = 2.718281828459045
print(np.sin(np.pi / 2)) # 正弦
print(np.cos(np.pi / 2)) # 余弦
print(np.tan(np.pi / 2)) # 正切
print(np.arcsin(1)) # 反正弦
print(np.arccos(1)) # 反余弦
print(np.arctan(1)) # 反正切
print(np.degrees(np.pi)) # 将角度从弧度转换为度 180.0
print(np.radians(180)) # 将角度从度转换为弧度 3.141592653589793
# 指数与对数
print(np.exp(np.array([1, 2])))
print(np.log(np.array([1, 2])))
5、排序与求和
代码语言:javascript复制import numpy as np
a = np.array([[5, 3],
[4, 2]])
print(np.sort(a, 0)) # 列排序
[[4 2]
[5 3]]
print(np.sort(a, 1)) # 行排序
[[3 5]
[2 4]]
print(np.sum(a, 0)) # 列求和
[9 5]
print(np.sum(a, 1)) # 行求和
[8 6]