Inverted Fancy Indexing

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

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

But is there a quick way to select all array data 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)) 

thanks

+4
source share
1 answer

Look numpy.invert , numpy.bitwise_not , numpy.logical_not or more succinctly ~mask . (In this case, they all do the same.)

As a quick example:

 import numpy as np x = np.arange(10) mask = x > 5 print x[mask] print x[~mask] 
+6
source

Source: https://habr.com/ru/post/1383149/


All Articles