轉自:
http://blog.csdn.net/zine_123/article/details/51746567
常用統計函數:
求和:sum()、均值:mean()、標準差:std()、方差:var()、最小值:min()、最大值:max()、最大值與最小值之差:ptp()、最大值的下標:argmax()、最小值的下標:argmin()、中值:median()
上述函數都可以指定axis,來沿着某一軸操作;除了mean()函數求均值,還可以使用average(),並且可以指定weights參數來指定權值,計算加權平均;argmax()和argmin()如果不指定axis參數,則返回平坦化後的下標;
排序函數:sort()、argsort();數組的sort()方法會對數組本身進行改變,而sort()函數則不會;sort默認axis=-1,即沿着最後一個軸進行排序;sort()函數返回一個新的排序後的數組而argsort()則返回排序後的下標數組,如:
import numpy as np
a = np.random.randint(0,10,size=(4,5))
array([[8, 2, 0, 3, 7],
[7, 0, 2, 7, 4],
[1, 8, 1, 1, 2],
[4, 6, 2, 1, 4]])
a.sort() #此時a數組會改變爲排序後的數組;
a1 = np.sort(a) #此時a數組不變,得到的a1數組爲:
array([[0, 2, 3, 7, 8],
[0, 2, 4, 7, 7],
[1, 1, 1, 2, 8],
[1, 2, 4, 4, 6]])
# 即沿着-1軸排序後的結果 對每行按列排序
>>> a2 = np.sort(a,axis = 0)
>>> a2
array([[3, 0, 2, 6, 2],
[4, 3, 3, 7, 2],
[5, 6, 5, 7, 2],
[7, 8, 9, 8, 4]])
# 即沿着0軸排序後的結果 對每列按行排序
idx = np.argsort(a)
idx
array([[2, 1, 3, 4, 0],
[1, 2, 4, 0, 3],
[0, 2, 3, 4, 1],
[3, 2, 0, 4, 1]])
此時,雖然idx.shape = (4,5),但是並不能直接使用a[idx]得到排序後的數組,因爲idx是數組,所以numpy會在後面補:,等效於:a[idx,:],idx數組中的每個值訪問a數組的0軸,當idx中的值超過a的0軸長度之後就會產生錯誤:IndexError: index 4 is out of bounds for axis 0 with size 4;所以使用idx來訪問a得到排序後的數組,需要產生0軸的下標,通過np.ogrid對象可以生成:
x,_ = np.ogrid[:a.shape[0],:a.shape[1]]
右邊的表達式生成a數組的grid,即各個軸的下標數組,取第一個元素即得到a數組的0軸下標數組:
array([[0],
[1],
[2],
[3]])
通過a[x,idx]可以正確訪問到排序後的數組