为什么我的数组在Numpy中执行多维索引后丢失了它的掩码?

2024-03-28 10:20:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望使用多维MaskedArray作为索引数组:

数据:

In [149]: np.ma.arange(10, 60, 2)
Out[149]: 
masked_array(data = [10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58],
             mask = False,
       fill_value = 999999)

指标:

^{pr2}$

期望输出:

In [151]: np.ma.arange(10, 60, 2)[np.ma.array(np.arange(20).reshape(4, 5), mask=np.arange(20).reshape(4, 5) % 3)]
Out[151]: 
masked_array(data =
 [[10 -- -- 16 --]
 [-- 22 -- -- 28]
 [-- -- 34 -- --]
 [40 -- -- 46 --]],
             mask =
 False,
       fill_value = 999999)

实际产量:

In [160]: np.ma.arange(10, 60, 2)[np.ma.array(np.arange(20).reshape(4, 5), mask=np.arange(20).reshape(4, 5) % 3)]
Out[160]: 
masked_array(data =
 [[10 12 14 16 18]
 [20 22 24 26 28]
 [30 32 34 36 38]
 [40 42 44 46 48]],
             mask =
 False,
       fill_value = 999999)

为什么生成的数组会丢失它的掩码?根据这里的答案:Indexing with Masked Arrays in numpy,这种索引方法非常糟糕。为什么?在


Tags: infalsedatavaluenpmask数组out
2条回答

看起来,使用掩码数组进行索引只是忽略了掩码。如果不深入研究文档或代码,我会说numpy数组索引没有屏蔽数组子类的特殊知识。得到的数组只是普通的arange(20)索引。在

但您可以执行普通索引,并“复制”遮罩:

In [13]: data=np.arange(10,60,2)

In [14]: mI = np.ma.array(np.arange(20).reshape(4,5),mask=np.arange(20).reshape(4,5) % 3)

...

In [16]: np.ma.array(data[mI], mask=mI.mask)
Out[16]: 
masked_array(data =
 [[10     16  ]
 [  22     28]
 [    34    ]
 [40     46  ]],
             mask =
 [[False  True  True False  True]
 [ True False  True  True False]
 [ True  True False  True  True]
 [False  True  True False  True]],
       fill_value = 999999)

您真的需要将索引和屏蔽合并到一个操作(和屏蔽数组)中吗。如果面罩是分开的,这个手术也能起到同样的效果。在

^{pr2}$

如果被屏蔽的索引元素无效(例如超出范围),可以用有效的内容填充它们(如果需要,在后面加上遮罩):

data[mI.filled(fill_value=0)]

你在numpy masked array文档中看到过一个使用masked数组索引另一个数组的例子吗?还是所有的屏蔽数组都是“数据”?有可能设计者从未打算让您使用屏蔽索引。在


掩码数组.choose之所以工作,是因为它使用了一个为屏蔽数组子类化的方法。常规索引可能会将索引转换为规则数组,其内容如下:data[np.asarray(mI)]。在


MaskedArray类的__getitem__方法启动:

    def __getitem__(self, indx):

        Return the item described by i, as a masked array.

        """
        # This test is useful, but we should keep things light...
#        if getmask(indx) is not nomask:
#            msg = "Masked arrays must be filled before they can be used as indices!"
#            raise IndexError(msg)

这是在屏蔽数组上执行[]时调用的方法。显然,开发人员考虑过正式禁止使用屏蔽索引,但认为这还不够重要。有关详细信息,请参见np.ma.core.py文件。在

尝试使用choose方法,如下所示:

np.ma.array(np.arange(20).reshape(4, 5), mask=np.arange(20).reshape(4, 5) % 3).
            choose(np.ma.arange(10, 60, 2))

它给出了:

^{pr2}$

相关问题 更多 >