Numpy inverse mask

36,944

Solution 1

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)

Solution 2

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]
Share:
36,944

Related videos on Youtube

ustroetz
Author by

ustroetz

GIS Developer at ally

Updated on July 09, 2022

Comments

  • ustroetz
    ustroetz almost 2 years

    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)
    
  • user508402
    user508402 over 7 years
    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