Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if numpy array contains only zeros

Tags:

python

numpy

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.

like image 240
IUnknown Avatar asked Aug 23 '13 05:08

IUnknown


People also ask

How do you check if all elements are zero in array?

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.

How do you check if a matrix is all zero?

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().

What is the use of zeros () function in NumPy?

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.


1 Answers

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()
  • This is preferred over numpy.all(a==0) because it uses less RAM. (It does not require the temporary array created by the a==0 term.)
  • Also, it is faster than numpy.count_nonzero(a) because it can return immediately when the first nonzero element has been found.
    • Edit: As @Rachel pointed out in the comments, np.any() no longer uses "short-circuit" logic, so you won't see a speed benefit for small arrays.
like image 147
Stuart Berg Avatar answered Sep 24 '22 18:09

Stuart Berg