Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverted fancy indexing

Having an array and a mask for this array, using fancy indexing, it is easy to select only the data of the array corresponding to the mask.

import numpy as np

a = np.arange(20).reshape(4, 5)
mask = [0, 2]
data = a[:, mask]

But is there a rapid way to select all the data of the array that does not belong to the mask (i.e. the mask is the data we want to reject)? I tried to find a general solution going through an intermediate boolean array, but I'm sure there is something really easier.

mask2 = np.ones(a.shape)==1
mask2[:, mask]=False
data = a[mask2].reshape(a.shape[0], a.shape[1]-size(mask))

Thank you

like image 376
gcalmettes Avatar asked Nov 26 '11 02:11

gcalmettes


1 Answers

Have a look at numpy.invert, numpy.bitwise_not, numpy.logical_not, or more concisely ~mask. (They all do the same thing, in this case.)

As a quick example:

import numpy as np

x = np.arange(10)
mask = x > 5

print x[mask]
print x[~mask]
like image 200
Joe Kington Avatar answered Oct 20 '22 18:10

Joe Kington