Numpy inverse mask

ustroetz picture ustroetz · May 24, 2013 · Viewed 25.1k times · Source

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

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)

Answer

Joran Beasley picture Joran Beasley · May 24, 2013
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)