Given a numpy array, the task is to check whether the numpy array contains all zeroes or not. Let’s discuss few ways to solve the above task. Method #1: Getting count of Zeros using numpy.count_nonzero()
Python3
# Python code to demonstrate # to count the number of elements # in numpy which are zero import numpy as np ini_array1 = np.array([ 1 , 2 , 3 , 4 , 5 , 6 , 0 ]) ini_array2 = np.array([ 0 , 0 , 0 , 0 , 0 , 0 ]) # printing initial arrays print ( "initial arrays" , ini_array1) print (ini_array2) # code to find whether all elements are zero countzero_in1 = np.count_nonzero(ini_array1) countzero_in2 = np.count_nonzero(ini_array2) # printing result print ( "Number of non-zeroes in array1 : " , countzero_in1) print ( "Number of non-zeroes in array2 : " , countzero_in2) |
initial arrays [1 2 3 4 5 6 0] [0 0 0 0 0 0] Number of non-zeroes in array1 : 6 Number of non-zeroes in array2 : 0
Time complexity: O(n)
The count_nonzero() function iterates through the entire input array to count the number of non-zero elements.
Auxiliary space complexity: O(1)
The code only uses a constant amount of extra space to store the input arrays and the count of non-zero elements.
Method #2: Using numpy.any()
Python3
# Python code to check that whether # all elements in numpy are zero import numpy as np ini_array1 = np.array([ 1 , 2 , 3 , 4 , 5 , 6 , 0 ]) ini_array2 = np.array([ 0 , 0 , 0 , 0 , 0 , 0 ]) # printing initial arrays print ( "initial arrays" , ini_array1) # code to find whether all elements are zero countzero_in1 = not np. any (ini_array1) countzero_in2 = not np. any (ini_array2) # printing result print ( "Whole array contains zeroes in array1 ?: " , countzero_in1) print ( "Whole array contains zeroes in array2 ?: " , countzero_in2) |
initial arrays [1 2 3 4 5 6 0] Whole array contains zeroes in array1 ?: False Whole array contains zeroes in array2 ?: True
Method #3: Using numpy.count_nonzero
Check if all values in array are zero using np.count_nonzero()
Python3
import numpy as np # Initialize the numpy arrays array1 = np.array([ 1 , 2 , 3 , 4 , 5 , 6 , 0 ]) array2 = np.array([ 0 , 0 , 0 , 0 , 0 , 0 ]) # Check if all values in array1 are zero if np.count_nonzero(array1) = = 0 : print ( "Array 1: all values are zero? True" ) else : print ( "Array 1: all values are zero? False" ) # Check if all values in array2 are zero if np.count_nonzero(array2) = = 0 : print ( "Array 2: all values are zero? True" ) else : print ( "Array 2: all values are zero? False" ) #This code is contributed by Edula Vinay Kumar Reddy |
This will give output as:
Array 1: all values are zero? False
Array 2: all values are zero? True