我有两个 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
的元素?
只需使用 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]])