Dada la array numpy, la tarea es encontrar elementos dentro de un rango específico. Vamos a discutir algunas formas de hacer la tarea.
Método #1: Usarnp.where()
# python code to demonstrate # finding elements in range # in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 810, 9, 6]) # printing initial array print("initial_array : ", str(ini_array)); # find elements in range 6 to 10 result = np.where(np.logical_and(ini_array>= 6, ini_array<= 10)) # printing result print("resultant_array : ", result)
Producción:
initial_array : [ 1 2 3 45 4 7 810 9 6] resultant_array : (array([5, 7, 8]),)
Método #2: Usarnumpy.searchsorted()
# Python code to demonstrate # finding elements in range # in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6]) # printing initial array print("initial_array : ", str(ini_array)); # find elements in range 6 to 10 start = np.searchsorted(ini_array, 6, 'left') end = np.searchsorted(ini_array, 10, 'right') result = np.arange(start, end) # printing result print("resultant_array : ", result)
Producción:
initial_array : [ 1 2 3 45 4 7 9 6] resultant_array : [5 6 7]
Método #3: Usando *
# Python code to demonstrate # finding elements in range # in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6]) # printing initial array print("initial_array : ", str(ini_array)); # find elements in range 6 to 10 result = ini_array[(ini_array>6)*(ini_array<10)] # printing result print("resultant_array : ", result)
Producción:
initial_array : [ 1 2 3 45 4 7 9 6] resultant_array : [7 9]
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