23

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)
ustroetz
  • 5,802
  • 16
  • 47
  • 74

2 Answers2

44
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)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Copying your example, I find different results for logical_not and the tilde operator. Where the former results in the expected mask ([[ True False True]]), the latter makes all mask elements True – user508402 Nov 29 '16 at 15:26
7

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

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

result = data[~mask]
Safi
  • 152
  • 1
  • 11
  • It would be much better to be explicit and say which Python version precisely. I have no clue which was the latest Python version back in 2018.11.18. – msoutopico Dec 11 '22 at 15:40