Home > Enterprise >  How can I perform the "reverse" of numpy argwhere?
How can I perform the "reverse" of numpy argwhere?

Time:03-12

Suppose I have a boolean numpy array, and I perform np.argwhere() on it. Is there any way to easily and efficiently do the reverse operation? In other words, given the final shape of a, and the results of argwhere(), how can I find a? I've tried to use the argwhere results together with an array full of False, but can't figure out how to use to do it. Maybe somehow use np.where()?

>>> a = np.array([[False,  True, False,  True, False],
                  [False, False,  True, False, False]])
>>> results = np.argwhere(a)
>>> results
array([[0, 1],
       [0, 3],
       [1, 2]], dtype=int64)
>>> recover_a = np.full(shape=a.shape, fill_value=False)  # I am  
>>> # guessing I could start here then do something...

CodePudding user response:

Use results columns as indices to update the value in recover_a:

recover_a[results[:,0], results[:,1]] = True

recover_a
# array([[False,  True, False,  True, False],
#        [False, False,  True, False, False]])

CodePudding user response:

In [233]: a = np.array([[False, True, False, True, False], [False, False, True,
     ...: False, False]])
In [234]: np.argwhere(a)
Out[234]: 
array([[0, 1],
       [0, 3],
       [1, 2]])
In [235]: np.nonzero(a)
Out[235]: (array([0, 0, 1]), array([1, 3, 2]))

argwhere is just the np.transpose(np.nonzero(a)). One is a tuple of arrays, the other a 2d array with those arrays arranged as columns.

The nonzero/where result is better for indexing, since it is a tuple of indices.

In [236]: res = np.zeros(a.shape, bool)
In [237]: res[np.nonzero(a)] = True
In [238]: res
Out[238]: 
array([[False,  True, False,  True, False],
       [False, False,  True, False, False]])

In [239]: a[np.nonzero(a)]
Out[239]: array([ True,  True,  True])
  • Related