Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find numpy array values bounding an input value

Tags:

python

numpy

I have a value, say 2016 and a sorted numpy array: [2005, 2010, 2015, 2020, 2025, 2030]. What is the pythonic way to find the 2 values in the array that bound 2016. In this case, the answer will be an array [2015, 2020].

Not sure how to do it other than loop, but hoping for a more numpy based solution

--EDIT:

you can assume that you will never get a value that is in the array, I prefilter for that

like image 851
user308827 Avatar asked Mar 12 '23 23:03

user308827


1 Answers

A straight-forward approach would be with np.searchsorted -

idx = np.searchsorted(A,B,'left')
out = A[idx],A[idx+1]

Explanation

The inputs are -

In [27]: A
Out[27]: [2005, 2010, 2015, 2020, 2025, 2030]

In [28]: B
Out[28]: 2015

Find the index where B should sit in A to maintain the sorted nature with searchsorted. This would correspond to the lower bound index. So, index into A with index and index+1 for the two bounding values -

In [29]: idx = np.searchsorted(A,B,'left')

In [30]: idx
Out[30]: 2

In [31]: A[idx],A[idx+1]
Out[31]: (2015, 2020)
like image 180
Divakar Avatar answered Mar 23 '23 09:03

Divakar