Python | Find elements within range in numpy
Given numpy array, the task is to find elements within some specific range. Let’s discuss some ways to do the task.
Method #1: Using np.where()
import numpy as np
ini_array = np.array([ 1 , 2 , 3 , 45 , 4 , 7 , 810 , 9 , 6 ])
print ( "initial_array : " , str (ini_array));
result = np.where(np.logical_and(ini_array> = 6 , ini_array< = 10 ))
print ( "resultant_array : " , result)
|
Output:
initial_array : [ 1 2 3 45 4 7 810 9 6]
resultant_array : (array([5, 7, 8]),)
Method #2: Using numpy.searchsorted()
import numpy as np
ini_array = np.array([ 1 , 2 , 3 , 45 , 4 , 7 , 9 , 6 ])
print ( "initial_array : " , str (ini_array));
start = np.searchsorted(ini_array, 6 , 'left' )
end = np.searchsorted(ini_array, 10 , 'right' )
result = np.arange(start, end)
print ( "resultant_array : " , result)
|
Output:
initial_array : [ 1 2 3 45 4 7 9 6]
resultant_array : [5 6 7]
Method #3: Using *
import numpy as np
ini_array = np.array([ 1 , 2 , 3 , 45 , 4 , 7 , 9 , 6 ])
print ( "initial_array : " , str (ini_array));
result = ini_array[(ini_array> 6 ) * (ini_array< 10 )]
print ( "resultant_array : " , result)
|
Output:
initial_array : [ 1 2 3 45 4 7 9 6]
resultant_array : [7 9]
Last Updated :
12 Mar, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...