Dada una array numpy, la tarea es verificar si la array numpy contiene todos los ceros o no. Analicemos algunas formas de resolver la tarea anterior.
Método #1: Obtener el conteo de ceros usandonumpy.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)
Producción:
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
Método #2: Usarnumpy.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)
Producción:
initial arrays [1 2 3 4 5 6 0] Whole array contains zeroes in array1 ?: False Whole array contains zeroes in array2 ?: True
Publicación traducida automáticamente
Artículo escrito por garg_ak0109 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA