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,其对应的元素的y是True:
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相应值的元素y是True?
只需使用布尔索引:
>>> 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)
| 归档时间: |
|
| 查看次数: |
1373 次 |
| 最近记录: |