w3resource logo
Python Exercises

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

Python NumPy: Array Object Exercise-63 with Solution

Write a Python program to get the number of nonzero elements in an array.

Sample Solution:-

Python Code:

import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print("Original array:")
print(x)
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 

Python Code Editor:

import numpy as np
x = np.array([[0, 10, 20], [20, 30, 40]])
print("Original array:")
print(x)
print("Number of non zero elements in the above array:")
print(np.count_nonzero(x))

Improve this sample solution and post your code through Disqus