python最接近某个值怎么表示,Python / Numpy - 快速查找最接近某些值的数组中的索引...

I have an array of values, t, that is always in increasing order (but not always uniformly spaced). I have another single value, x. I need to find the index in t such that t[index] is closest to x. The function must return zero for x < t.min() and the max index (or -1) for x > t.max().

I've written two functions to do this. The first one, f1, is MUCH quicker in this simple timing test. But I like how the second one is just one line. This calculation will be done on a large array, potentially many times per second.

Can anyone come up with some other function with comparable timing to the first but with cleaner looking code? How about something quicker then the first (speed is most important)?

Thanks!

Code:

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)

解决方案

This seems much quicker (for me, Python 3.2-win32, numpy 1.6.0):

from bisect import bisect_left

def f3(t, x):

i = bisect_left(t, x)

if t[i] - x > 0.5:

i-=1

return i

Output:

[ 10 11 12 ..., 99997 99998 99999]

37854.22200356027

37844

37844

37844

37854

37854

37854

f1 0.332725

f2 1.387974

f3 0.085864

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值