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
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])
print("initial arrays", ini_array1)
print(ini_array2)
countzero_in1 = np.count_nonzero(ini_array1)
countzero_in2 = np.count_nonzero(ini_array2)
print("Number of non-zeroes in array1 : ", countzero_in1)
print("Number of non-zeroes in array2 : ", countzero_in2)
|
Output: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
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])
print("initial arrays", ini_array1)
countzero_in1 = not np.any(ini_array1)
countzero_in2 = not np.any(ini_array2)
print("Whole array contains zeroes in array1 ?: ", countzero_in1)
print("Whole array contains zeroes in array2 ?: ", countzero_in2)
|
Output: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
array1 = np.array([1, 2, 3, 4, 5, 6, 0])
array2 = np.array([0, 0, 0, 0, 0, 0])
if np.count_nonzero(array1) == 0:
print("Array 1: all values are zero? True")
else:
print("Array 1: all values are zero? False")
if np.count_nonzero(array2) == 0:
print("Array 2: all values are zero? True")
else:
print("Array 2: all values are zero? False")
|
This will give output as:
Array 1: all values are zero? False
Array 2: all values are zero? True
Last Updated :
13 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...