NumPy count_nonzero() - Count the number of non-zero elements in an array

The count_nonzero() counts the number of non-zero elements in a NumPy array.

import numpy

a1 = numpy.array([5, 0, 9, 1])
a2 = numpy.array([[1, 0, 0, 1], [1, 1, 0, 2]])

c1 = numpy.count_nonzero(a1)
c2 = numpy.count_nonzero(a2)

print(c1)  # 3
print(c2)  # 5

NumPy Array

NumPy Tutorial