39

我现在已经多次阅读屏蔽数组文档,到处搜索,感觉非常愚蠢。我无法弄清楚如何将掩码从一个阵列应用到另一个阵列。

例子:

import numpy as np

y = np.array([2,1,5,2])          # y axis
x = np.array([1,2,3,4])          # x axis
m = np.ma.masked_where(y>2, y)   # filter out values larger than 5
print m
[2 1 -- 2]
print np.ma.compressed(m)
[2 1 2]

所以这很好....但是要绘制这个 y 轴,我需要一个匹配的 x 轴。如何将 y 数组中的掩码应用于 x 数组?这样的事情是有道理的,但会产生垃圾:

new_x = x[m.mask].copy()
new_x
array([5])

那么,到底是如何完成的(注意新的 x 数组需要是一个新数组)。

编辑:

好吧,这样做的一种方法似乎是这样的:

>>> import numpy as np
>>> x = np.array([1,2,3,4])
>>> y = np.array([2,1,5,2])
>>> m = np.ma.masked_where(y>2, y)
>>> new_x = np.ma.masked_array(x, m.mask)
>>> print np.ma.compressed(new_x)
[1 2 4]

但这真是令人难以置信的混乱!我正在尝试找到一个像 IDL 一样优雅的解决方案......

4

3 回答 3

26

我有一个类似的问题,但涉及加载更多的屏蔽命令和更多的数组来应用它们。我的解决方案是我在一个数组上进行所有屏蔽,然后使用最终屏蔽的数组作为mask_where命令中的条件。

例如:

y = np.array([2,1,5,2])                         # y axis
x = np.array([1,2,3,4])                         # x axis
m = np.ma.masked_where(y>5, y)                  # filter out values larger than 5
new_x = np.ma.masked_where(np.ma.getmask(m), x) # applies the mask of m on x

好消息是您现在可以将此掩码应用于更多数组,而无需对每个数组进行掩码过程。

于 2013-08-15T09:53:07.537 回答
20

为什么不简单

import numpy as np

y = np.array([2,1,5,2])          # y axis
x = np.array([1,2,3,4])          # x axis
m = np.ma.masked_where(y>2, y)   # filter out values larger than 5
print list(m)
print np.ma.compressed(m)

# mask x the same way
m_ = np.ma.masked_where(y>2, x)   # filter out values larger than 5
# print here the list
print list(m_) 
print np.ma.compressed(m_)

代码适用于 Python 2.x

此外,正如 joris 所提议的,这可以new_x = x[~m.mask].copy()提供一个数组

>>> new_x
array([1, 2, 4])
于 2013-05-11T09:06:57.843 回答
1

这可能不是 100% OP 想知道的,但它是我一直在使用的一段可爱的小代码——如果你想以相同的方式屏蔽多个数组,你可以使用这个通用函数来屏蔽一个动态数量的 numpy一次数组:

def apply_mask_to_all(mask, *arrays):
assert all([arr.shape == mask.shape for arr in arrays]), "All Arrays need to have the same shape as the mask"
return tuple([arr[mask] for arr in arrays])

请参阅此示例用法:

    # init 4 equally shaped arrays
x1 = np.random.rand(3,4)
x2 = np.random.rand(3,4)
x3 = np.random.rand(3,4)
x4 = np.random.rand(3,4)

# create a mask
mask = x1 > 0.8

# apply the mask to all arrays at once
x1, x2, x3, x4 = apply_mask_to_all(m, x1, x2, x3, x4)
于 2020-11-23T18:30:05.843 回答