can*_*bag 3 python arrays numpy
我有一个这样的有序数组: numpy.array([1, 2, 5, 10, 25, 36, 66, 90, 121, 230, 333, 500])
假设我希望所有值都达到60(如果60不在,我想停在第一个值大于60),所以我想要[1, 2, 5, 10, 25, 36, 66].如果我使用numpy.where()<= 60,它会在66之前停止.
我的解决方案
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]
Run Code Online (Sandbox Code Playgroud)
And*_*nca 10
有一个特定的numpy函数来做到这一点np.searchsorted,它比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
Run Code Online (Sandbox Code Playgroud)
更值得注意的是,它还包含一个特定的关键字side,包括或不包括最后一点:
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])
Run Code Online (Sandbox Code Playgroud)