1

如何获取所有未屏蔽元素的索引?以下是我正在努力解决的一个例子。我有两个大小相等的 numpy 数组,x 和 m。现在我想使用数组 m 作为 x 上的掩码来提取未掩码值的值和索引。我认为一些代码会更好地解释

numpy 数组 x & m

>>> x = np.array([[3,5,9],[6,0,7],[2,3,4]])
>>> x
array([[3, 5, 9],
       [6, 0, 7],
       [2, 3, 4]])
>>> m = np.array([[1,1,2],[2,1,1],[2,1,2]])
>>> m
array([[1, 1, 2],
       [2, 1, 1],
       [2, 1, 2]])

现在我想提取 x 的值,其中 m 等于 1

>>> mo = ma.array(m,mask=(m<>1))
>>> mo
masked_array(data =
 [[1 1 --]
 [-- 1 1]
 [-- 1 --]],
             mask =
 [[False False  True]
 [ True False False]
 [ True False  True]],
       fill_value = 999999)

>>> xm = ma.masked_array(x,mask=mo.mask, dtype=int)
>>> xm
masked_array(data =
 [[3 5 --]
 [-- 0 7]
 [-- 3 --]],
             mask =
 [[False False  True]
 [ True False False]
 [ True False  True]],
       fill_value = 999999)

我想要掩码为假的值的索引。现在我可以使用 ma 库中的非零函数,但我的数组也包含零值。可以看出,[1,1]缺少值:

>>> xmindex = np.transpose(ma.MaskedArray.nonzero(xm))
>>> xmindex
array([[0, 0],
       [0, 1],
       [1, 2],
       [2, 1]])

简而言之,如何获取所有未屏蔽元素的索引,而不仅仅是非零值?

4

2 回答 2

3

如上所述,我会尝试使用 numpy.where():

x = np.array([[3,5,9],[6,0,7],[2,3,4]])
m = np.array([[1,1,2],[2,1,1],[2,1,2]])
indices = np.where(m == 1)  # indices contains two arrays, the column and row indices
values = x[indices]

干杯!

于 2013-07-15T08:45:02.373 回答
0

这是一种可能性。但我几乎可以肯定它太迂回了。

>>> xmindex = np.transpose(np.concatenate(((ma.MaskedArray.nonzero(xm==0), 
              ma.MaskedArray.nonzero(xm!=0))),axis=1))
>>> xmindex
array([[1, 1],
       [0, 0],
       [0, 1],
       [1, 2],
       [2, 1]])

然后排序

>>> xmindex = xmindex[np.lexsort((xmindex[:,1],xmindex[:,0]))]
>>> xmindex
array([[0, 0],
       [0, 1],
       [1, 1],
       [1, 2],
       [2, 1]])
于 2013-07-15T07:52:52.547 回答