numpy:ndenumerate用于蒙面数组?

时间:2011-12-23 21:30:47

标签: python numpy

是否可以枚举屏蔽numpy ndarray的非屏蔽位置(例如,ndenumerate对常规ndarrays执行此操作的方式,但省略所有屏蔽的条目)?

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

谢谢!

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

2 个答案:

答案 0 :(得分: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

有关详细信息,请参阅this

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

>>> 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

答案 1 :(得分:2)

怎么样:

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

产生

(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
相关问题