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

Bal*_*sar 28 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]
Run Code Online (Sandbox Code Playgroud)

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

new_x = x[m.mask].copy()
new_x
array([5])
Run Code Online (Sandbox Code Playgroud)

那么,究竟是怎么做的(注意新的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]
Run Code Online (Sandbox Code Playgroud)

但那令人难以置信的凌乱!我正在努力寻找像IDL一样优雅的解决方案......

kir*_*off 18

为什么不简单

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_)
Run Code Online (Sandbox Code Playgroud)

代码适用于Python 2.x.

另外,正如joris所提出的,这是做new_x = x[~m.mask].copy()数组的工作

>>> new_x
array([1, 2, 4])
Run Code Online (Sandbox Code Playgroud)

  • 避免使用“简单”、“只是”等词可能有助于您的回答。 (5认同)

red*_*ger 17

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

好处是你现在可以将这个掩码应用于更多的数组,而无需通过每个数组的掩蔽过程.