Fix Python – Test if numpy array contains only zeros

Question

Asked By – IUnknown

We initialize a numpy array with zeros as bellow:

np.zeros((N,N+1))

But how do we check whether all elements in a given n*n numpy array matrix is zero.
The method just need to return a True if all the values are indeed zero.

Now we will see solution for issue: Test if numpy array contains only zeros


Answer

Check out numpy.count_nonzero.

>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5

This question is answered By – Prashant Kumar

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0