Reputation: 73
Let's say I have the following numpy array of time points of a certain measurement, where it can be assumed that it is ordered from small to large:
time_points = np.array([0.4, 0.8, 1.2, 2.0, 2.4, 2.8, 3.2, 3.6])
I would like to find the index of the last element that is lower or equal to three. In this example the element is 2.8
and the index is 5
. So I would like a python code that gives me that 5
. A relatively short code can do this:
index = 0
while time_points[index] <= 3:
index += 1
index -= 1
But my time_points
array can get very long and I was wondering if there is a faster way, just like the method index()
to do this in only one line? Something like
>>> time_points = np.array([0.4, 0.8, 1.2, 2.0, 2.4, 2.8, 3.2, 3.6])
>>> index = function(time_points, 3)
5
Or perhaps code with multiple lines, but that uses the numpy
library to make the operation faster.
Thanks in advance!
Upvotes: 7
Views: 3779
Reputation: 136
numpy.searchsorted is literally the exact function you need.
It uses binary search to find the closest point, where it "cuts" the list in half everytime and only looks at that half.
It can be used like this, say arr is the list.
>>> arr = np.array([0.4, 0.8, 1.2, 2.0, 2.4, 2.8, 3.2, 3.6])
>>> arr.searchsorted(3, 'right') - 1
5
>>> arr.searchsorted(2.8, 'right') - 1
5
>>> arr.searchsorted(0, 'right') - 1 # No greater item
-1
I doubt there is a faster numpy method as this is a one liner, and uses binary search which is generally the fastest search method on a sorted array.
Upvotes: 6