Python Numpy 逆掩码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16724669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:26:41  来源:igfitidea点击:

Numpy inverse mask

pythonarraysnumpymask

提问by ustroetz

I want to inverse the true/false value in my numpy masked array.

我想反转我的 numpy 掩码数组中的真/假值。

So in the example below i don't want to mask out the second value in the data array, I want to mask out the first and third value.

所以在下面的例子中,我不想屏蔽数据数组中的第二个值,我想屏蔽掉第一个和第三个值。

Below is just an example. My masked array is created by a longer process than runs before. So I can not change the mask array itself. Is there another way to inverse the values?

下面只是一个例子。我的掩码数组是由比以前更长的过程创建的。所以我不能改变掩码数组本身。还有另一种方法可以反转值吗?

import numpy
data = numpy.array([[ 1, 2, 5 ]])
mask = numpy.array([[0,1,0]])

numpy.ma.masked_array(data, mask)

采纳答案by Joran Beasley

import numpy
data = numpy.array([[ 1, 2, 5 ]])
mask = numpy.array([[0,1,0]])

numpy.ma.masked_array(data, ~mask) #note this probably wont work right for non-boolean (T/F) values
#or
numpy.ma.masked_array(data, numpy.logical_not(mask))

for example

例如

>>> a = numpy.array([False,True,False])
>>> ~a
array([ True, False,  True], dtype=bool)
>>> numpy.logical_not(a)
array([ True, False,  True], dtype=bool)
>>> a = numpy.array([0,1,0])
>>> ~a
array([-1, -2, -1])
>>> numpy.logical_not(a)
array([ True, False,  True], dtype=bool)

回答by Safi

Latest Python version also support '~' character as 'logical_not'. For Example

最新的 Python 版本也支持 '~' 字符作为 'logical_not'。例如

import numpy
data = numpy.array([[ 1, 2, 5 ]])
mask = numpy.array([[False,True,False]])

result = data[~mask]