Change language

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" = 6 , ini_array " = 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" 6 ) * (ini_array " 10 )]

 
# print result

print ( "resultant_array:" , result)

Exit:

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

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method