使用一维布尔数组过滤二维数组

3

我有两个numpy数组。

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

我希望获得y中对应元素为TrueX元素:

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

我尝试过使用np.extract,但似乎仅适用于1维数组x。当y对应的值为True时,如何提取x中的元素?


1
x[y]。这被称为布尔索引。 - P. Camilleri
你可以尝试使用列表推导式,例如[val for val in x if y[x.index(val)]]。简单而优雅。 - Asad Moosvi
@AsadMoosvi 比 numpy 内置函数慢,而且不返回 np.array... - P. Camilleri
2个回答

11

只需使用布尔索引即可:

>>> 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]])

4
为了保持一致性和清晰度,我更喜欢使用 x[y, :] 和 x[:, y]。 - Jblasco
2
我倾向于省略结尾的 , :,因为这样更省打字,而且结果是否包含它们并没有区别。但是我可以理解包含它们会更容易理解。 :) - MSeifert

0

l=[x[i] for i in range(0,len(y)) if y[i]] 这样就可以了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接