2011-12-23 132 views
5

有沒有一種方法可以枚舉掩碼爲numpy ndarray的非掩碼位置(例如,ndenumerate對於常規的ndarrays執行的操作,但省略了所有掩碼條目)?numpy:掩碼數組的ndenumerate?

編輯:更確切地說:枚舉不僅應該跳過掩碼條目,還要顯示原始數組中非掩碼條目的索引。例如。如果一維數組的前五個元素被屏蔽,並且下一個元素的未屏蔽值爲3,則枚舉應該從((5,), 3), ...開始。

謝謝! PS:請注意,雖然可以將ndenumerate應用於掩碼爲ndarray的枚舉,但枚舉不會區分其掩碼條目和正常條目。實際上,ndenumerate不僅不會過濾掉枚舉中的掩碼條目,而且它甚至不會使用常量替換枚舉值。因此,只需用合適的過濾器包裝ndenumerate,就無法使ndenumerate適應此任務。

+0

看看毫安陣列的壓縮功能 – tillsten 2011-12-25 23:01:15

回答

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 
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 
相關問題