The Python Oracle

Find indices of elements equal to zero in a NumPy array

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5

--

Chapters
00:00 Question
00:30 Accepted answer (Score 289)
00:58 Answer 2 (Score 54)
01:20 Answer 3 (Score 29)
01:39 Answer 4 (Score 26)
02:06 Thank you

--

Full question
https://stackoverflow.com/questions/4588...

Question links:
[nonzero()]: http://docs.scipy.org/doc/numpy/referenc...

Accepted answer links:
[numpy.where()]: http://docs.scipy.org/doc/numpy/referenc...

Answer 2 links:
[np.argwhere]: https://docs.scipy.org/doc/numpy/referen...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #numpy

#avk47



ACCEPTED ANSWER

Score 305


numpy.where() is my favorite.

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.where(x == 0)[0]
array([1, 3, 5])

The method where returns a tuple of ndarrays, each corresponding to a different dimension of the input. Since the input is one-dimensional, the [0] unboxes the tuple's only element.




ANSWER 2

Score 29


You can search for any scalar condition with:

>>> a = np.asarray([0,1,2,3,4])
>>> a == 0 # or whatver
array([ True, False, False, False, False], dtype=bool)

Which will give back the array as an boolean mask of the condition.




ANSWER 3

Score 28


You can also use nonzero() by using it on a boolean mask of the condition, because False is also a kind of zero.

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])

>>> x==0
array([False, True, False, True, False, True, False, False, False, False, False], dtype=bool)

>>> numpy.nonzero(x==0)[0]
array([1, 3, 5])

It's doing exactly the same as mtrw's way, but it is more related to the question ;)




ANSWER 4

Score 7


If you are working with a one-dimensional array there is a syntactic sugar:

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.flatnonzero(x == 0)
array([1, 3, 5])