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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With