numpy官方文档:https://numpy.org/doc/stable/
pip install numpy
import numpy as np
¶ 矩阵定义
= np.array([[1,2],[3,4]]) a
¶ reshape
https://numpy.org/doc/stable/reference/generated/numpy.reshape.html
¶ 求行列式
np.linalg.det(a)
LINear ALGebra
¶ 矩阵拼接
竖直拼接用vstack:
= np.zeros((0, 3)) # 0行3列的矩阵
res = np.vstack([res, [1, 2, 3]])
res = np.vstack([res, [4, 5, 6]])
res res
array([[1., 2., 3.],
[4., 5., 6.]])
水平拼接用hstack,语法跟上面的一样。
¶ 求均值
= np.array([[1., 2., 3.], [4., 5., 6.]])
m # 整个矩阵所有值的平均数
m.mean() =0) # 将第0维干掉。实际上就是求每列的平均数
m.mean(axis=1) # 将第1维干掉。实际上就是求每行的平均数 m.mean(axis
要求标准差的话,把上面的mean
换成std
即可。
¶ 每隔n个元素求均值
import numpy as np
= np.array([1, 4, 2, 3, 5, 6])
a = 2
n -1, n).mean(axis=1) a.reshape(
如果长度不是n的倍数的话,只能这样:
def mean_every_n(a, n):
= len(a) - len(a) % n
split = a[0:split].reshape(-1, n).mean(axis=1)
res if split != len(a):
= np.append(res, a[split:].mean())
res return res
4) mean_every_n(a,
参考:https://www.geeksforgeeks.org/averaging-over-every-n-elements-of-a-numpy-array/#
¶ percentile
https://numpy.org/doc/stable/reference/generated/numpy.percentile.html#
# 10000个0到1的随机数
= np.random.rand(10000)
a # 求20%分位数,即小于此数的值的数量占总数的20%
20)
np.percentile(a, # 求多个分位数
10, 20, 30, 40, 50, 60, 70, 80, 90, 99, 99.9, 99.99]) np.percentile(a, [