2017-09-01 95 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]]这将做到这一点。