I often use the numpy.where function to collect index index tuples of a matrix that has some property. for instance
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 row and column indexes, while the subexpression X> 0.5 contains one boolean matrix indicating which cells had property> 0.5. Each view has its own advantages.
What is the best way to take an ix object and convert it back to boolean later when needed? for instance
G = np.zeros(X.shape,dtype=np.bool) >>> G[ix] = True
Is there a single line that does the same thing?
source share