2017-09-01 88 views
1

我有兩個numpy數組。其中y相應元素的使用1d布爾陣列的FIlter 2d陣列

x = [[1,2], [3,4], [5,6]] 
y = [True, False, True] 

我想獲得的X元素是True

filtered_x = filter(x,y) 
print(filtered_x) # [[1,2], [5,6]] should be shown. 

我試過np.extract,但它似乎只工作時x是一維數組。我如何提取x對應的值y的元素是True

+1

x [y]。它被稱爲布爾索引。 –

+0

您可以嘗試使用列表理解,例如'[val for x in x [x.index(val)]]]'。簡單而優雅。 –

+0

@AsadMoosvi和比numpy內置函數慢,也不返回np.array ... –

回答

6

只需使用boolean indexing

>>> import numpy as np 

>>> x = np.array([[1,2], [3,4], [5,6]]) 
>>> y = np.array([True, False, True]) 
>>> x[y] # or "x[y, :]" because the boolean array is applied to the first dimension (in this case the "rows") 
array([[1, 2], 
     [5, 6]]) 

而如果你想它適用於列,而不是行:

>>> x = np.array([[1,2], [3,4], [5,6]]) 
>>> y = np.array([True, False]) 
>>> x[:, y] # boolean array is applied to the second dimension (in this case the "columns") 
array([[1], 
     [3], 
     [5]]) 
+3

爲了一致性和清晰度,我更喜歡x [y,:]和x [:,y] – Jblasco

+2

我傾向於喜歡省略後綴'::',因爲輸入的內容更多,並且如果包含它們或省略它們,結果不會有差異。但我可以看到它更容易理解。 :) – MSeifert

0

l=[x[i] for i in range(0,len(y)) if y[i]]這將做到這一點。