【问题标题】:numpy: ndenumerate for masked arrays?numpy:屏蔽数组的 ndenumerate?
【发布时间】:2011-12-23 21:30:46
【问题描述】:

有没有办法枚举被屏蔽的numpy ndarray 的非屏蔽位置(例如,ndenumerate 对常规 ndarrays 进行枚举,但忽略所有被屏蔽的条目)?

编辑:更准确地说:枚举不仅应该跳过被屏蔽的条目,还应该显示原始数组中非屏蔽条目的索引。例如。如果一维数组的前五个元素被屏蔽,而下一个元素的未屏蔽值为 3,则枚举应以 ((5,), 3), ... 之类的内容开头。

谢谢!

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

【问题讨论】:

  • 看看ma数组的压缩函数

标签: python numpy


【解决方案1】:

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

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

【讨论】:

    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2017-08-19
      • 2021-01-14
      • 1970-01-01
      相关资源
      最近更新 更多