w3resource

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

NumPy: Array Object Exercise-115 with Solution

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

Python-Numpy Code Editor:

Previous: Write a NumPy program to create random set of rows from 2D array.
Next: Write a NumPy program to compute the histogram of a set of data.

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.