【问题标题】:FIlter 2d array using 1d boolean array [duplicate]使用一维布尔数组过滤二维数组[重复]
【发布时间】:2018-02-10 13:23:48
【问题描述】:

我有两个 numpy 数组。

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

我想获取X的元素,其中y的对应元素是True

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

我试过np.extract,但它似乎只在x 是一维数组时才有效。如何提取x的元素,y对应的值为True

【问题讨论】:

  • x[y]。这称为布尔索引。
  • 您可以尝试使用[val for val in x if y[x.index(val)]] 之类的列表解析。简洁大方。
  • @AsadMoosvi 并且比 numpy 内置函数慢,并且也不返回 np.array...

标签: python arrays numpy


【解决方案1】:

只需使用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]])

【讨论】:

  • 为了一致性和清晰性,我更喜欢 x[y, :] 和 x[:, y]
  • 我倾向于省略尾随, :,因为它需要更多的输入,并且如果我包含或省略它们,结果不会有所不同。但我可以看出哪里更容易理解。 :)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-01-26
    • 2018-12-28
    • 2013-06-23
    • 2022-01-23
    • 2013-06-09
    • 2019-09-04
    • 2011-05-24
    • 2015-07-26
    相关资源
    最近更新 更多