Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy inverse mask

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)
like image 915
ustroetz Avatar asked May 23 '13 22:05

ustroetz


2 Answers

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)
like image 51
Joran Beasley Avatar answered Oct 20 '22 18:10

Joran Beasley


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]
like image 29
Safi Avatar answered Oct 20 '22 19:10

Safi