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.
if(array[i] == 0) instead of if(array[i] = 0) ? = is assignment, and you want to keep looping until either the first non-zero value or the end.
A matrix could sum to zero without every element being zero. If you want every element being zero, you need to take abs() before summing, or use nnz().
The zeros() function is used to get a new array of given shape and type, filled with zeros. Shape of the new array, e.g., (2, 3) or 2. The desired data-type for the array, e.g., numpy. int8.
The other answers posted here will work, but the clearest and most efficient function to use is numpy.any()
:
>>> all_zeros = not np.any(a)
or
>>> all_zeros = not a.any()
numpy.all(a==0)
because it uses less RAM. (It does not require the temporary array created by the a==0
term.)numpy.count_nonzero(a)
because it can return immediately when the first nonzero element has been found.np.any()
no longer uses "short-circuit" logic, so you won't see a speed benefit for small arrays.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With