Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting indices of a specific value in numpy array

Tags:

python

numpy

I have the foll. numpy array:

arr = [0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1]

This is how I am getting the indices of all 0's in the array:

inds = []
for index,item in enumerate(arr):     
    if item == 0:
        inds.append(index)

Is there a numpy function to do the same?

like image 331
user308827 Avatar asked Feb 08 '23 08:02

user308827


2 Answers

You could use numpy.argwhere as @chappers pointed out in the comment:

arr = np.array([0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1])

In [34]: np.argwhere(arr == 0).flatten()
Out[34]:
array([ 0,  1,  2,  4,  5,  6,  7,  8,  9, 10, 12, 14, 16, 17, 18, 19, 20,
       21, 22, 23, 24, 25], dtype=int32)

Or with inverse of astype(bool):

In [63]: (~arr.astype(bool)).nonzero()[0]
Out[63]:
array([ 0,  1,  2,  4,  5,  6,  7,  8,  9, 10, 12, 14, 16, 17, 18, 19, 20,
       21, 22, 23, 24, 25], dtype=int32)
like image 176
Anton Protopopov Avatar answered Feb 12 '23 12:02

Anton Protopopov


>>> arr = np.array([0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1])
>>> (arr==0).nonzero()[0]
array([ 0,  1,  2,  4,  5,  6,  7,  8,  9, 10, 12, 14, 16, 17, 18, 19, 20,
       21, 22, 23, 24, 25])
like image 27
John La Rooy Avatar answered Feb 12 '23 12:02

John La Rooy