numpy:ndenumerate用于蒙面数组?

kjo*_*kjo 5 python numpy

有没有办法枚举被屏蔽的非掩码位置numpy ndarray(例如,ndenumerate以常规方式ndarrays,但省略所有被屏蔽的条目)?

编辑:更精确:枚举不仅应该跳过掩码条目,还要显示原始数组中非掩码条目的索引.例如,如果1-d数组的前五个元素被屏蔽,而下一个元素的未屏蔽值为3,那么枚举应该以类似的方式开始((5,), 3), ....

谢谢!

PS:请注意,尽管可以应用于ndenumerate屏蔽ndarray,但结果枚举不会区分其屏蔽和正常条目.实际上,ndenumerate它不仅不会从枚举中过滤掉屏蔽的条目,而且甚至不会用枚举替换枚举值masked.因此,ndenumerate只需ndenumerate用合适的过滤器包裹就不能适应这项任务.

Ale*_*man 7

您只能使用掩码的反转作为索引来访问有效条目:

>>> import numpy as np
>>> import numpy.ma as ma
>>> x = np.array([11, 22, -1, 44])
>>> m_arr = ma.masked_array(x, mask=[0, 0, 1, 0])
>>> for index, i in np.ndenumerate(m_arr[~m_arr.mask]): 
        print index, i
(0,) 11
(1,) 22
(2,) 44
Run Code Online (Sandbox Code Playgroud)

请参阅了解详情.

仅对包含原始数组的索引的有效条目进行枚举:

>>> for (index, val), m in zip(np.ndenumerate(m_arr), m_arr.mask):
      if not m:
        print index, val 
(0,) 11
(1,) 22
(3,) 44
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 4

怎么样:

import numpy as np
import itertools

def maenumerate(marr):
    mask = ~marr.mask.ravel()
    for i, m in itertools.izip(np.ndenumerate(marr), mask):
        if m: yield i

N = 12
a = np.arange(N).reshape(2, 2, 3)+10

b = np.ma.array(a, mask = (a%5 == 0))
for i, val in maenumerate(b):
    print i, val
Run Code Online (Sandbox Code Playgroud)

这产生

(0, 0, 1) 11
(0, 0, 2) 12
(0, 1, 0) 13
(0, 1, 1) 14
(1, 0, 0) 16
(1, 0, 1) 17
(1, 0, 2) 18
(1, 1, 0) 19
(1, 1, 2) 21
Run Code Online (Sandbox Code Playgroud)