<p>看起来,使用掩码数组进行索引只是忽略了掩码。如果不深入研究文档或代码,我会说<code>numpy</code>数组索引没有屏蔽数组子类的特殊知识。得到的数组只是普通的<code>arange(20)</code>索引。在</p>
<p>但您可以执行普通索引,并“复制”遮罩:</p>
<pre><code>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)
</code></pre>
<p>您真的需要将索引和屏蔽合并到一个操作(和屏蔽数组)中吗。如果面罩是分开的,这个手术也能起到同样的效果。在</p>
^{pr2}$
<p>如果被屏蔽的索引元素无效(例如超出范围),可以用有效的内容填充它们(如果需要,在后面加上遮罩):</p>
<pre><code>data[mI.filled(fill_value=0)]
</code></pre>
<p>你在numpy masked array文档中看到过一个使用masked数组索引另一个数组的例子吗?还是所有的屏蔽数组都是“数据”?有可能设计者从未打算让您使用屏蔽索引。在</p>
<hr/>
<p>掩码数组<code>.choose</code>之所以工作,是因为它使用了一个为屏蔽数组子类化的方法。常规索引可能会将索引转换为规则数组,其内容如下:<code>data[np.asarray(mI)]</code>。在</p>
<hr/>
<p><code>MaskedArray</code>类的<code>__getitem__</code>方法启动:</p>
<pre><code> 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)
</code></pre>
<p>这是在屏蔽数组上执行<code>[]</code>时调用的方法。显然,开发人员考虑过正式禁止使用屏蔽索引,但认为这还不够重要。有关详细信息,请参见<code>np.ma.core.py</code>文件。在</p>