使用1d布尔数组的2d数组

rkj*_*983 2 python arrays numpy

我有两个numpy数组.

x = [[1,2], [3,4], [5,6]]
y = [True, False, True]
Run Code Online (Sandbox Code Playgroud)

我想获得的元素X,其对应的元素的yTrue:

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

我试过了np.extract,但它似乎只在x1d数组时工作.如何提取x相应值的元素yTrue

MSe*_*ert 9

只需使用布尔索引:

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

如果您想将其应用于列而不是行:

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

  • 为了一致性和清晰度,我更喜欢x [y,:]和x [:,y] (3认同)
  • 我倾向于省略尾随`,:`因为它更多的是键入,如果我包含它们或省略它们,结果不会有所不同.但我可以看到它更容易理解的地方.:) (2认同)