4

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?

2
  • 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]) convert to array for clarity and then ... >>> np.where(arr==0) (array([ 0, 1, 2, 4, 5, ..., 21, 22, 23, 24, 25]),) is one method. slice the where with [0] just to get the indices Commented Dec 7, 2015 at 4:12
  • is numpy.argwhere what you're after? Something like numpy.argwhere(arr == 0) Commented Dec 7, 2015 at 4:14

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

3
>>> 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])

2 Comments

thanks @John, what does the [0] at the end of nonzero do?
@user308827, nonzero returns a tuple of arrays, one for each dimension of arr. You only have one dimension, but you still need [0] there to pull it out of the tuple

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.