In this python numpy program, we will get the number of nonzero elements in an array using NumPy.
Steps to solve the program
- Import the numpy library as np.
- Create an array using np.array().
- Get the number of nonzero elements in an array using np.count_nonzero().
- Print the output.
import numpy as np
x = np.array([[4, 8, 0],[2, 0, 6]])
print("Number of non-zero elements: ",np.count_nonzero(x))
Output :
Number of non-zero elements: 4