2015-02-10 75 views
0

假設我有一個2d numpy數組,並且我想過濾每個行通過特定條件的元素。例如,我只想要其特定行以上的第90百分位以上的元素。我想出了這個解決方案:具有行特定條件的過濾器numpy數組

import numpy as np 
a = np.random.random((6,5)) 
thresholds = np.percentile(a, 90, axis=1) 
threshold_2d = np.vstack([thresholds]*a.shape[1]).T 
mask = a > threshold_2d 
final = np.where(mask, a, np.nan) 

它的工作原理和它的矢量,但感覺有點尷尬,尤其是在我創建threshold_2d一部分。有沒有更優雅的方式?我能以某種方式自動廣播np.where的條件而不必創建匹配的2d掩碼?

回答

2

廣播

In [36]: np.random.seed(1023) 

In [37]: a = np.random.random((6,5)) 

In [38]: thresholds = np.percentile(a, 90, axis=1) 

In [39]: threshold_2d = np.vstack([thresholds]*a.shape[1]).T 

In [40]: a>threshold_2d 
Out[40]: 
array([[ True, False, False, False, False], 
     [False, False, True, False, False], 
     [False, True, False, False, False], 
     [False, False, False, True, False], 
     [False, False, False, False, True], 
     [False, True, False, False, False]], dtype=bool) 

In [41]: a>thresholds[:,np.newaxis] 
Out[41]: 
array([[ True, False, False, False, False], 
     [False, False, True, False, False], 
     [False, True, False, False, False], 
     [False, False, False, True, False], 
     [False, False, False, False, True], 
     [False, True, False, False, False]], dtype=bool) 

In [42]: 

numpy.newaxis創建長度之一的軸,所得到的陣列視圖具有的尺寸(6,1),並且可以與a arrray進行廣播。