如何将一个数组中的蒙版应用于另一个数组? [英] how to apply a mask from one array to another array?

查看:100
本文介绍了如何将一个数组中的蒙版应用于另一个数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了几次遮罩数组文档,在各处搜索并且感到非常愚蠢.我一生都无法弄清楚如何将一个面罩从一个阵列应用到另一个阵列.

I've read the masked array documentation several times now, searched everywhere and feel thoroughly stupid. I can't figure out for the life in me how to apply a mask from one array to another.

示例:

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数组?这样的事情是有道理的,但是会产生垃圾:

So this works fine.... but to plot this y axis, I need a matching x axis. How do I apply the mask from the y array to the x array? Something like this would make sense, but produces rubbish:

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

那么,到底是怎么完成的(请注意,新的x数组必须是新的数组).

So, how on earth is that done (note the new x array needs to be a new array).

好吧,看来这样做的一种方法是这样的:

Well, it seems one way to do this works like this:

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

But that's incredibly messy! I'm trying to find a solution as elegant as IDL...

推荐答案

为什么不简单

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

code is for Python 2.x

此外,正如joris所建议的那样,这可以完成new_x = x[~m.mask].copy()给出数组的工作

Also, as proposed by joris, this do the work new_x = x[~m.mask].copy() giving an array

>>> new_x
array([1, 2, 4])

这篇关于如何将一个数组中的蒙版应用于另一个数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆