我有两个numpy数组。
x = [[1,2], [3,4], [5,6]]
y = [True, False, True]
我希望获得y
中对应元素为True
的X
元素:
filtered_x = filter(x,y)
print(filtered_x) # [[1,2], [5,6]] should be shown.
我尝试过使用np.extract
,但似乎仅适用于1维数组x
。当y
对应的值为True
时,如何提取x
中的元素?
只需使用布尔索引即可:
>>> 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]])
, :
,因为这样更省打字,而且结果是否包含它们并没有区别。但是我可以理解包含它们会更容易理解。 :) - MSeifertl=[x[i] for i in range(0,len(y)) if y[i]]
这样就可以了。
[val for val in x if y[x.index(val)]]
。简单而优雅。 - Asad Moosvi