当前位置: 代码迷 >> python >> Python / numpy:数组中的所有值都是x?
  详细解决方案

Python / numpy:数组中的所有值都是x?

热度:134   发布时间:2023-07-16 10:23:48.0

我有一个这样的有序数组: 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]

有一个特定的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

更显着地,它也有一个特定的关键字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])

你不需要任何特殊的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]