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

參考影片:嗶哩嗶哩——馬士兵教育-楊淑娟