import numpy as np
不同轴求和
x = np.array([[1,2,],[3,4]])
print(x.sum()) # 所有元素求和
print(x.sum(axis=0)) # 按列(0轴)求和
print(x.sum(axis=1)) # 按行(1轴)求和
10
[4 6]
[3 7]
求和后保持维度不变
x.sum(axis=0,keepdims=True)
array([[4, 6]])
指定运算后的返回值类型
x.sum(axis=0,dtype=np.float32)
array([ 4., 6.], dtype=float32)
x = np.array([1,3,2])
print(x.min())
print(x.max())
print(x.argmin())#最小值的索引
print(x.argmax())#最大值的索引
1
3
0
1
a = np.random.randint(0,10,size=(4,5))
mean()求平均数
a.mean(axis=1)
array([ 5.6, 6.2, 1.2, 3.6])
average()求加权平均数
score = np.array([83,72,79])
number = np.array([20,15,20])
np.average(score,weights=number)
78.545454545454547
np.random.seed(42)
a = np.random.randint(0,8,10)
print(a)
print(np.bincount(a)) # 0为出现,1出现1次,2出现1次,3出现1次,4出现4次,依次类推
[6 3 4 6 2 7 4 4 6 1]
[0 1 1 1 3 0 3 1]
为每个数指定权重,权重累加
x = np.array([0,1,2,2,1,1,0])
w = np.array([0.1,0.3,0.2,0.4,0.5,0.8,1.2])
np.bincount(x,w)
array([ 1.3, 1.6, 0.6])
求每个数的加权平均数
np.bincount(x,w)/np.bincount(x)
array([ 0.65 , 0.53333333, 0.3 ])
a = np.random.rand(100)
np.histogram(a,bins=5,range=(0,1))#在[0,0.2)有28个数,在[0.2,0.4)有18个数,以此类推
(array([28, 18, 17, 19, 18], dtype=int64),
array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. ]))
若要统计的区间不等,可以将表示区间分割位置的数组传递给bins参数
np.histogram(a,bins=[0,0.4,0.8,1.0])
(array([46, 36, 18], dtype=int64), array([ 0. , 0.4, 0.8, 1. ]))