Skip to content
Related Articles

Related Articles

Improve Article

Python | Check if all values in numpy are zero

  • Last Updated : 12 Mar, 2019

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




# 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)
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

 
Method #2: Using numpy.any()




# Python code to check that whether
# all elemenst 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)
Output:
initial arrays [1 2 3 4 5 6 0]
Whole array contains zeroes in array1 ?:  False
Whole array contains zeroes in array2 ?:  True

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :