2D Numpy蒙版无法按预期工作 [英] 2d numpy mask not working as expected

查看:87
本文介绍了2D Numpy蒙版无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过删除选择索引将2x3的numpy数组转换为2x2的数组.

I'm trying to turn a 2x3 numpy array into a 2x2 array by removing select indexes.

我想我可以使用具有正确/错误值的掩码数组来做到这一点.

I think I can do this with a mask array with true/false values.

给予

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

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

I want to remove one element from each row to give me:

 [ 2,  3],
 [ 4,  6]

但是这种方法无法正常工作:

However this method isn't working quite like I would expect:

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]

这不是我想要的.有什么想法吗?

Which is not what I want. Any ideas?

推荐答案

唯一有问题的是形状-1d而不是2.但是如果您的口罩是那样的话

The only thing 'wrong' with that is it is the shape - 1d rather than 2. But what if your mask was

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

第一行中为1,第二行中为2.它无法将其作为二维数组返回,是吗?

1 value in the first row, 2 in second. It couldn't return that as a 2d array, could it?

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

So the default behavior when masking like this is to return a 1d, or raveled result.

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

Boolean indexing like this is effectively a where indexing:

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的相应元素.

It finds the elements of the mask which are true, and then selects the corresponding elements of the in_array.

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

Maybe the transpose of where is easier to visualize:

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

这篇关于2D Numpy蒙版无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆