VOOZH about

URL: https://www.geeksforgeeks.org/python/find-indices-of-elements-equal-to-zero-in-a-numpy-array/

⇱ Find Indices of Elements Equal to Zero in a NumPy Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find Indices of Elements Equal to Zero in a NumPy Array

Last Updated : 27 Sep, 2025

It means you want to find the positions (row and column indices) where the elements of a NumPy array are equal to zero. For example, Given the array [[1, 0, 3], [0, 5, 6], [7, 8, 0]], find the row and column indices of all elements equal to zero.

Using numpy.nonzero()

The numpy.nonzero() function returns the indices of non-zero elements. By applying a condition, we can use it to find positions of zeros.

Example: In this example, we create a 1-D array and use np.nonzero() to locate zero values.


Output
Array: [ 1 10 2 0 3 9 0 5 0 7 5 0 0]
Indices of zero elements: (array([ 3, 6, 8, 11, 12]),)

Explanation

  • arr == 0 creates a boolean array where True marks zero positions.
  • np.nonzero() returns the indices where True occurs.

Using numpy.where()

The numpy.where() function returns indices where a condition holds true. It’s one of the most common ways to locate elements.

Example: Here, we use np.where() to find the indices of zeros in a 1-D array.


Output
Array: [1 0 2 0 3 0 0 5 6 7 5 0 8]
Indices of zero elements: [ 1 3 5 6 11]

Explanation:

  • arr == 0 creates a boolean mask.
  • np.where() extracts the indices of True values.
  • [0] is added to flatten the result into a 1-D array.

Using numpy.argwhere()

The numpy.argwhere() function returns the indices of elements that satisfy a condition, grouped by row/column in multi-dimensional arrays.

Example: In this example, we use a 2-D array and find all zero indices using np.argwhere().


Output
Array:
[[0 2 3]
 [4 1 0]
 [0 0 2]]
Indices of zero elements:
[[0 0]
 [1 2]
 [2 0]
 [2 1]]

Explanation

  • arr == 0 marks the zero elements.
  • np.argwhere() returns their positions as coordinate pairs [row, col].

Using numpy.extract()

The numpy.extract() function returns elements that satisfy a condition. By combining it with np.arange(), we can extract the indices of zeros.

Example: Here, we use np.extract() to directly get the indices of zeros in a 1-D array.


Output
Array: [1 0 2 0 3 0 0 5 6 7 5 0 8]
Indices of zero elements: [ 1 3 5 6 11]

Explanation:

  • arr == 0 creates a mask.
  • np.arange(len(arr)) generates index positions.
  • np.extract() selects indices where the condition is True.
Comment
Article Tags: