+4 votes
in Programming Languages by (56.5k points)
I want to find the indices of all array elements that are not zero. Which Python function should I use?

1 Answer

+4 votes
by (348k points)
selected by
 
Best answer

You can use the where() or the argwhere() or the flatnonzero() function of Numpy.

Here is an example:

>>> import numpy as np
>>> a=np.array([10,11,32,43,21,454,0,45,10,0,12,0,54])
>>> a
array([ 10,  11,  32,  43,  21, 454,   0,  45,  10,   0,  12,   0,  54])
>>> np.argwhere(a)
array([[ 0],
       [ 1],
       [ 2],
       [ 3],
       [ 4],
       [ 5],
       [ 7],
       [ 8],
       [10],
       [12]])

>>> np.argwhere(a).flatten()
array([ 0,  1,  2,  3,  4,  5,  7,  8, 10, 12])
>>>

>>> np.where(a!=0)[0]
array([ 0,  1,  2,  3,  4,  5,  7,  8, 10, 12])
>>>

>>> np.flatnonzero(a)
array([ 0,  1,  2,  3,  4,  5,  7,  8, 10, 12])
 


...