numpy矩阵操作
阅读量:
searchstar
2021-08-20 22:09:42
Categories:
Tags:
numpy官方文档:https://numpy.org/doc/stable/
¶ 矩阵定义
a = np.array([[1 ,2 ],[3 ,4 ]])
¶ reshape
https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
¶ 求行列式
LINear ALGebra
¶ 矩阵拼接
竖直拼接用vstack:
res = np.zeros((0 , 3 )) res = np.vstack([res, [1 , 2 , 3 ]]) res = np.vstack([res, [4 , 5 , 6 ]]) res
array([[1., 2., 3.], [4., 5., 6.]])
水平拼接用hstack,语法跟上面的一样。
¶ 求均值
m = np.array([[1. , 2. , 3. ], [4. , 5. , 6. ]]) m.mean() m.mean(axis=0 ) m.mean(axis=1 )
要求标准差的话,把上面的mean
换成std
即可。
¶
每隔n个元素求均值
import numpy as npa = np.array([1 , 4 , 2 , 3 , 5 , 6 ]) n = 2 a.reshape(-1 , n).mean(axis=1 )
如果长度不是n的倍数的话,只能这样:
def mean_every_n (a, n ): split = len (a) - len (a) % n res = a[0 :split].reshape(-1 , n).mean(axis=1 ) if split != len (a): res = np.append(res, a[split:].mean()) return res mean_every_n(a, 4 )
参考:https://www.geeksforgeeks.org/averaging-over-every-n-elements-of-a-numpy-array/#
¶
每列除以某个向量
matrix = np.array([[1 , 2 , 3 ], [4 , 5 , 6 ], [7 , 8 , 9 ]]) vector = np.array([1 , 2 , 3 ]) column_vector = vector[:, np.newaxis] matrix / column_vector
array([[1. , 2. , 3. ], [2. , 2.5 , 3. ], [2.33333333, 2.66666667, 3. ]])
¶ 参考文献
python中矩阵的用法
numpy创建矩阵常用方法
numpy.mean()
计算矩阵均值