w3resource

NumPy: Find indices of elements equal to zero in a NumPy array


Find Indices of Elements Equal to Zero

Write a NumPy program to find the indices of elements equal to zero in a NumPy array.

Sample Solution:

Python Code:

# Importing the NumPy library and aliasing it as 'np'
import numpy as np

# Creating a NumPy array 'nums' containing integers
nums = np.array([1, 0, 2, 0, 3, 0, 4, 5, 6, 7, 8])

# Printing a message indicating the original array will be displayed
print("Original array:")

# Printing the original array 'nums'
print(nums)

# Finding the indices of elements equal to zero in the array 'nums'
# Using np.where() to find the indices where the elements are equal to 0 and accessing the first (and only) array of indices
result = np.where(nums == 0)[0]

# Printing the indices of elements equal to zero in the array 'nums'
print("Indices of elements equal to zero of the said array:")
print(result) 

Sample Output:

Original array:
[1 0 2 0 3 0 4 5 6 7 8]
Indices of elements equal to zero of the said array:
[1 3 5]

Explanation:

In the above code –

nums = np.array([1,0,2,0,3,0,4,5,6,7,8]): Create a NumPy array 'nums' containing the specified integer values.

np.where(nums == 0): Use the np.where() function to find the indices of elements in the 'nums' array that are equal to 0. The expression nums == 0 creates a boolean array of the same shape as 'nums', with True at the positions where the element is 0 and False elsewhere.

np.where(nums == 0)[0]: The np.where() function returns a tuple, but we are only interested in the first element of that tuple (the array of indices). To extract the first element, we use the index [0]. Store the array of indices to the variable 'result'.

print(result): Print the resulting 'result' array.

Pictorial Presentation:

Python NumPy: Find indices of elements equal to zero in a NumPy array

For more Practice: Solve these Related Problems:

  • Write a NumPy program to find the indices of zero-valued elements in a 1D array using np.where.
  • Create a function that returns the index positions of all zeros in a multi-dimensional array after flattening.
  • Test the zero-index finder on an array with sporadic zeros and verify the output against manual indexing.
  • Implement a solution that highlights the zero elements in the original array by printing their coordinates.

Go to:


PREV : Generate Random Rows from 2D Array
NEXT : Compute Histogram of Data


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.