我有两个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
?
答案 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]]
这样就可以了。