Python | Find elements in a range in NumPy

Method # 1: Using np.where()

# Python code for demo
# search for items in a range
# in a NumPy array

import numpy as np

 

ini_array = np.array ([ 1 , 2 , 3 , 45 , 4 , 7 , 810 , 9 , 6 ])

 
# print the original array

print ( "initial_array:" , str (ini_array)); 

 
# find items in the range 6 to 10

result = np.where (np.logical_and (ini_array & gt; = 6 , ini_array & lt; = 10 ))

  
# print result

print ( " resultant_array: " , result)

Exit:

 initial_array: [1 2 3 45 4 7 810 9 6] resultant_array: (array ([ 5, 7, 8]),) 

Method # 2: Using numpy.searchsorted()

# Python code for demo
# search for items in a range
# in a NumPy array

  

import numpy as np

 

ini_array = np.array ([ 1 , 2 , 3 , 45 , 4 , 7 , 9 , 6 ])

  
# print the original array

print ( "initial_array:" , str (ini_array)); 

 

 
# find items between 6 and 10

start = np.searchsorted (ini_array, 6 , `left` )

end = np.searchsorted (ini_array, 10 , `right` )

result = np.arange (start, end)

 
# print result

print ( "resultant_array: " , result)

Output:

 initial_array: [1 2 3 45 4 7 9 6] resultant_array: [5 6 7] 

Method # 3: Usage *

# Python code to demonstrate
# search for items in a range
# in NumPy array

 

import numpy as np

 

ini_array = np.array ([ 1 , 2 , 3 , 45 , 4 , 7 , 9 , 6 ])

 
# print source array

print ( "initial_array: " , str (ini_array)); 

 

 
# find items between 6 and 10

result = ini_array [(ini_array & gt; 6 ) * (ini_array & lt; 10 )]

 
# print result

print ( "resultant_array:" , result)

Exit:

 initial_array: [1 2 3 45 4 7 9 6] resultant_array: [7 9]