如何将掩码从一个数组应用到另一个数组?

时间:2013-05-11 08:34:46

标签: python numpy

我现在已经多次阅读过蒙面数组文档,到处搜索并感到非常愚蠢。我无法弄清楚我的生活如何将面具从一个阵列应用到另一个阵列。

示例:

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一样优雅的解决方案......

3 个答案:

答案 0 :(得分:17)

为什么不简单

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

答案 1 :(得分:16)

我有类似的问题,但涉及加载更多屏蔽命令和更多数组来应用它们。我的解决方案是我在一个数组上执行所有屏蔽,然后使用finally掩码数组作为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

好处是你现在可以将这个掩码应用于更多的数组,而无需对每个数组进行掩码处理。

答案 2 :(得分:0)

这可能不是OP想要知道的100%, 但这是我一直使用的一小段代码- 如果要以相同的方式屏蔽多个数组,则可以使用以下通用函数一次屏蔽动态数量的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)
相关问题