w3resource

NumPy: Get the number of nonzero elements in an array

NumPy: Array Object Exercise-63 with Solution

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.

Python-Numpy Code Editor:

Previous: Write a NumPy program to split an of array of shape 4x4 it into two arrays along the second axis.
Next: Write a NumPy program to create a 5x5 matrix with row values ranging from 0 to 4.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-63.php