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

时间:2017-09-01 13:05:15

标签: python arrays numpy

我有两个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是1d数组时它似乎才有用。如何提取x y的相应值True的元素是SELECT DATE(start_date) trip_date, MAX(duration) FROM trips GROUP BY 1

2 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:0)

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