How to invert numpy.where (np.where) function How to invert numpy.where (np.where) function numpy numpy

How to invert numpy.where (np.where) function


Something like this maybe?

mask = np.zeros(X.shape, dtype='bool')mask[ix] = True

but if it's something simple like X > 0, you're probably better off doing mask = X > 0 unless mask is very sparse or you no longer have a reference to X.


mask = X > 0imask = np.logical_not(mask)

For example

Edit: Sorry for being so concise before. Shouldn't be answering things on the phone :P

As I noted in the example, it's better to just invert the boolean mask. Much more efficient/easier than going back from the result of where.


The bottom of the np.where docstring suggests to use np.in1d for this.

>>> x = np.array([1, 3, 4, 1, 2, 7, 6])>>> indices = np.where(x % 3 == 1)[0]>>> indicesarray([0, 2, 3, 5])>>> np.in1d(np.arange(len(x)), indices)array([ True, False,  True,  True, False,  True, False], dtype=bool)

(While this is a nice one-liner, it is a lot slower than @Bi Rico's solution.)