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

Setjmp picture Setjmp · Feb 29, 2012 · Viewed 8.8k times · Source

I frequently use the numpy.where function to gather a tuple of indices of a matrix having some property. For example

import numpy as np
X = np.random.rand(3,3)
>>> X
array([[ 0.51035326,  0.41536004,  0.37821622],
   [ 0.32285063,  0.29847402,  0.82969935],
   [ 0.74340225,  0.51553363,  0.22528989]])
>>> ix = np.where(X > 0.5)
>>> ix
(array([0, 1, 2, 2]), array([0, 2, 0, 1]))

ix is now a tuple of ndarray objects that contain the row and column indices, whereas the sub-expression X>0.5 contains a single boolean matrix indicating which cells had the >0.5 property. Each representation has its own advantages.

What is the best way to take ix object and convert it back to the boolean form later when it is desired? For example

G = np.zeros(X.shape,dtype=np.bool)
>>> G[ix] = True

Is there a one-liner that accomplishes the same thing?

Answer

Bi Rico picture Bi Rico · Feb 29, 2012

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.