我试图通过删除选择索引将2x3的numpy数组变成2x2的数组。

我想我可以使用具有true / false值的mask数组来做到这一点。

给定

 [ 1,  2,  3],
 [ 4,  1,  6]


我想从每一行中删除一个元素给我:

 [ 2,  3],
 [ 4,  6]


但是,此方法无法正常工作:

import numpy as np

in_array = np.array([
 [ 1,  2,  3],
 [ 4,  1,  6]
])

mask = np.array([
 [False,  True,  True],
 [True,   False, True]
])

print in_array[mask]


给我:

[2 3 4 6]


这不是我想要的。有任何想法吗?

最佳答案

唯一“错误”的是形状-1d而不是2。但是如果您的口罩是

mask = np.array([
 [False,  True,  False],
 [True,   False, True]
])


第一行中有1个值,第二行中有2个值。它不能将其作为2d数组返回,可以吗?

因此,像这样进行遮罩时的默认行为是返回1d或混乱的结果。

像这样的布尔索引实际上是where索引:

In [19]: np.where(mask)
Out[19]: (array([0, 0, 1, 1], dtype=int32), array([1, 2, 0, 2], dtype=int32))
In [20]: in_array[_]
Out[20]: array([2, 3, 4, 6])


它找到蒙版中正确的元素,然后选择in_array的相应元素。

也许where的转置更容易可视化:

In [21]: np.argwhere(mask)
Out[21]:
array([[0, 1],
       [0, 2],
       [1, 0],
       [1, 2]], dtype=int32)


并迭代索引:

In [23]: for ij in np.argwhere(mask):
    ...:     print(in_array[tuple(ij)])
    ...:
2
3
4
6

关于python - 2D Numpy蒙版无法按预期工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48874102/

10-11 01:01
查看更多