Python | Check if all values ​​in numpy are null

Arrays | NumPy | Python Methods and Functions

Method # 1: Getting the number of zeros using numpy.count_nonzero()

# Demo Python code
# count the number of items
# in NumPy that 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 ])

 
# print initial arrays

print ( "initial arrays" , ini_array1)

print (ini_array2)

  
# code to determine if all elements ratios are zero

countzero_in1 = np. count_nonzero (ini_array1)

countzero_in2 = np .count_nonzero (ini_array2)

 
# print result

print ( "Number of non-zeroes in array1:" , countzero_in1)

print ( "Number of non-zeroes in array2:" , countzero_in2)

Exit:

 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 if
# all elements in numpy are null

 

import numpy as np

 

ini_array1 = np.array ([ 1 , 2 , 3 , 4 , 5 , 6 , 0 ])

ini_array2 = < / code> np.array ([ 0 , 0 , 0 , 0 , 0 , 0 ])

 
# printing initial arrays

print ( "initial arrays" , ini_array1)

  
# code to determine if all elements are zero

countzero_in1 = not np. any (ini_array1)

countzero_in2 = not np. any (ini_array2)

 
# print result

print ( "Whole array contains zeroes in array1?:" , countzero_in1)

print ( "Whole array contains zeroes in array2?:" , countzero_in2)

Exit :

 initial arrays [1 2 3 4 5 6 0] Whole array contains zeroes in array1?: False Whole array contains zeroes in array2?: True 




Get Solution for free from DataCamp guru