w3resource

NumPy: Get the number of nonzero elements in an array


Count Non-Zero Elements in Array

Write a NumPy program to get the number of non-zero elements in an array.

Pictorial Presentation:

Python NumPy: Get the number of nonzero elements in an array

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a 2x3 NumPy array 'x' containing specific values
x = np.array([[0, 10, 20], [20, 30, 40]])

# Displaying the original 2x3 array 'x'
print("Original array:")
print(x)

# Counting the number of non-zero elements in the array 'x' using np.count_nonzero
print("Number of non-zero elements in the above array:")
print(np.count_nonzero(x))

Sample Output:

Original array:                                                        
[[ 0 10 20]                                                            
 [20 30 40]]                                                           
Number of non zero elements in the above array:                        
5 

Explanation:

In the above code –

‘x = np.array([[0, 10, 20], [20, 30, 40]])’ creates a 2D array x with the given elements.

print(np.count_nonzero(x)): The np.count_nonzero() function is used to count the number of non-zero elements in the array ‘x’. In this case, there are 5 non-zero elements in the array.


For more Practice: Solve these Related Problems:

  • Write a NumPy program to count the non-zero elements in a 2D array using np.count_nonzero.
  • Create a function that returns the indices and count of non-zero elements in an array.
  • Test the non-zero element count on arrays before and after modifying specific values to zero.
  • Use boolean indexing to filter out non-zero values and sum the count for validation.

Go to:


PREV : Split 4x4 Array Along Second Axis
NEXT : 5x5 Matrix with Row Values 0–4


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.