我有值,T的阵列,即总是递增次序(但不总是均匀间隔的)。我还有另一个值x。我需要在t中找到索引,使得t [index]最接近x。该函数必须为x < t.min()返回零,并为x> t.max()返回最大索引(或-1)。的Python/numpy的 - 快速查找索引数组中的最近的某个值
我已经写了两个函数来做到这一点。第一个,f1,在这个简单的时间测试中更快。但我喜欢第二个只是一条线。这个计算将在一个大阵列上完成,可能每秒多次。
任何人都可以拿出来与可比的时机一些其他的功能,第一,但与清洁寻找代码?第一个速度怎么样(速度是最重要的)?
谢谢!
代码:
import numpy as np
import timeit
t = np.arange(10,100000) # Not always uniform, but in increasing order
x = np.random.uniform(10,100000) # Some value to find within t
def f1(t, x):
ind = np.searchsorted(t, x) # Get index to preserve order
ind = min(len(t)-1, ind) # In case x > max(t)
ind = max(1, ind) # In case x < min(t)
if x < (t[ind-1] + t[ind])/2.0: # Closer to the smaller number
ind = ind-1
return ind
def f2(t, x):
return np.abs(t-x).argmin()
print t, '\n', x, '\n'
print f1(t, x), '\n', f2(t, x), '\n'
print t[f1(t, x)], '\n', t[f2(t, x)], '\n'
runs = 1000
time = timeit.Timer('f1(t, x)', 'from __main__ import f1, t, x')
print round(time.timeit(runs), 6)
time = timeit.Timer('f2(t, x)', 'from __main__ import f2, t, x')
print round(time.timeit(runs), 6)
由于您的数组进行排序,尝试二进制搜索。看到这个问题的答案︰http://stackoverflow.com/questions/212358/binary-search-in-python – payne 2011-05-19 23:04:38
我只是离开工作,但想看看这个稍后。我认为,一旦你测试了x max(t),你可能会通过短路改善你的第一个功能,但我还没有机会测试它。 –
2011-05-19 23:05:51