Python / numpy: all values ​​in an array up to x?

I have an ordered array: numpy.array([1, 2, 5, 10, 25, 36, 66, 90, 121, 230, 333, 500])

Suppose I need all values ​​up to 60 (if 60 is not found, I want to stop at the first value greater than 60), so I want to [1, 2, 5, 10, 25, 36, 66]. If I use numpy.where()with <= 60, it stops to 66.

My decision

from numpy import *
x = array([1, 2, 5, 10, 25, 36, 66, 90, 121, 230, 333, 500])
print x[:where(x >= 60)[0][0]+1]
>>>[ 1  2  5 10 25 36 66]
+3
source share
2 answers

For this you do not need anything special in numpy.

import numpy, bisect
a = numpy.array([1, 2, 5, 10, 25, 36, 66, 90, 121, 230, 333, 500])
idx = bisect.bisect(a, 60)
print a[:idx]
+2
source

there is a specific numpy function for this np.searchsorted, which is much faster than bisect.

a=np.arange(1e7)
c=2e6
%timeit bisect.bisect(a,c)
10000 loops, best of 3: 31.6 us per loop
%timeit np.searchsorted(a,c)
100000 loops, best of 3: 6.77 us per loop

More notably, it also has a specific keyword sidefor the inclusion or absence of the last point:

In [23]: a[:a.searchsorted(66,side='right')]
Out[23]: array([ 1,  2,  5, 10, 25, 36, 66])

In [24]: a[:a.searchsorted(66,side='left')]
Out[24]: array([ 1,  2,  5, 10, 25, 36])
+10
source

All Articles