python-函数-统计函数
# (1)amax(),amin() 作用:计算数组中的元素沿指定轴的最大值,最小值 import numpy as np
x = np.random.randint(1,11,9).reshape((3,3 )) print (x)
# output: [[ 9 1 2 ]
[ 5 2 6 ]
[ 10 10 3]]
print (np.amin(x,0)) # 每一列的最小值 print (np.amin(x,1 )) # 每一行的最小值 print (np.amax(x,0)) # 每一列的最大值 print (np.amax(x,1 )) # 每一行的最大值
# output: [5 1 2 ]
[ 1 2 3 ]
[ 10 10 6 ]
[ 9 6 10]
# (2)ptp() 作用:计算数组中元素最大值与最小值的差(最大值-最小值) import numpy as np
x = np.random.randint(1,11,9).reshape((3,3 )) print (x) print (np.ptp(x)) print (np.ptp(x,0)) print (np.ptp(x,1))
# output: [[10 6 2 ]
[ 2 10 10 ]
[ 6 5 10 ]] 8 [ 8 5 8 ]
[ 8 8 5]
# (3)percentile() 原型:numpy.percentile(a,p,axis) #a为数组 p为要计算的百分位数,在0~100之间,axis:沿着它计算百分比的轴 作用:百分位数是统计中使用的度量,表示小于这个值的观察值的百分比 x = np.array([[10,7,4],[3,2,1 ]]) print (x) print (np.percentile(x,50 )) print (np.percentile(x,50,axis= 0)) print (np.percentile(x,50,axis=1 ))
( 10+3)/2=6.5
# output: [[10 7 4 ]
[ 3 2 1 ]] 3.5 [ 6.5 4.5 2.5 ]
[ 7. 2.]
# (4)median() 作用:算数组中元素的中位数(中值) import numpy as np
x = np.array([[30,65,70],[80,95,10],[50,90,60 ]]) print (x) print ( " \n " ) print (np.median(x)) print (np.median(x,axis= 0)) print (np.median(x,axis=1))
# (5)mean() 作用:返回数组中元素的算数平方根 import numpy as np
x = np.arange(1,10).reshape((3,3 )) print ( " x数组: " ) print (x) print ( " \n " ) print (np.mean(x)) print (np.mean(x,axis= 0)) print (np.mean(x,axis=1))
# output: x数组:
[[ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ]] 5.0 [ 4. 5. 6 .]
[ 2. 5. 8.]
# (6)average()作用:根据在另一个数组中给出的各自权重计算数组中的元素的加权平均值,可以接受一个轴参数。如果没有指定轴,则数组会被展开 import numpy as np
x = np.array([1,2,3,4 ]) print (x) print (np.average(x))
wts = np.array([4,3,2,1 ]) print (np.average(x,weights= wts)) # 如果return 参数为true,则返回权重的和 print ( " 权重的和: " ) print (np.average([1,2,3,4],weights=[4,3,2,1],returned= True))
x = np.array([0,1,2,3,4,5]).reshape((3,2 )) print (x)
wts = np.array([3,5 ]) print (np.average(x,axis=1,weights= wts)) # (0*3+1*5)/(3+5)=5/8=0.625
# output: [1 2 3 4 ] 2.5 2.0 权重的和:
( 2.0, 10.0 )
[[0 1 ]
[ 2 3 ]
[ 4 5 ]]
[ 0.625 2.625 4.625]
# (7)标准差 公式: std = sqrt(mean((x-x.mean())**2)) 如果数组是[1,2,3,4],则其平均值为2.5,因此,差的平方是[2.25,0.25,0.25,2.25],并且其平均值的平方根除以4,即sqrt(5/4),结果为1.118033 ........
x = np.array([1,2,3,4 ]) print (x)
x - np.mean(x) 1.5*1.5 0.5*0.5 y = np.array([2.25,0.25,0.25,2.25 ])
np.mean(y)
np.sqrt( 1.25 ) # 也即 import numpy as np print (np.std([1,2,3,4]))
# output: [1 2 3 4 ] 1.118033988749895
# (8)方差. mean((x-x.mean())**2) 标准差是方差的平方根 print (np.var([1,2,3,4 ])) # 也即 x = np.array([1,2,3,4 ])
x - np.mean(x)
y = np.array([2.25,0.25,0.25,2.25 ]) print (y)
np.mean(y)
# output: 1.25 [ 2.25 0.25 0.25 2.25 ] 1.25
参考视频:哔哩哔哩——马士兵教育-杨淑娟