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

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?

+4
source share
4 answers

Something like this maybe?

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

but if it is something simple like X > 0 , you are probably better off doing mask = X > 0 if mask not very sparse or you no longer have a reference to X

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

- This is the default answer for the heartbeat (in terms of elegance, efficiency).

+1
source
 mask = X > 0 imask = np.logical_not(mask) 

for instance

Edit: Sorry for being so short. Do not answer questions by phone: P

As I noted in the example, it is better to just invert the boolean mask. Much more efficient / easier than returning to where result.

0
source

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

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

(Although this is a good one-liner, it is much slower than @Bi Rico's solution.)

0
source

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


All Articles