有效地匹配Python中的近似时间戳

时间:2015-10-07 09:12:59

标签: python

我有两个从两个独立传感器获得的时间戳列表,如下所示:

reference = [99999.0, 100000.0, 100001.0,...]

sensor = [99999.8234, 99999.9723, 100000.00123, ... , 100000.9924, 100001.02,...]

我希望有效地提取sensor中与reference中每个值最匹配的值的索引。

在上面的示例中,reference[0]是早于sensor[0]的时间戳,因此应该被丢弃。我希望代码返回[indexof(100000.00123), indexof(100000.9924)]

参考和传感器时间戳的列表已经排序。

我的尝试是这样的:

sensor_ind = []
ind = 0

for t in reference:
    last_diff = 999999999.99
    while np.fabs(sensor[ind]-t) < last_diff:
        last_diff = np.fabs(sensor[ind]-t)
        ind += 1

    sensor.append(ind)

print sensor

1 个答案:

答案 0 :(得分:1)

  def closest(l, R):

    from operator import itemgetter

    tupleList = zip(l,  [ abs(x - R) for x in l ])

    closeToR, delta  = sorted(tupleList, key=itemgetter(1)).pop(0)

    return closeToR  

for el in reference:
    print(closest(sensor,el))

99999.8234
100000.00123
100000.9924

of use bisect

你可以将bisect模块分开,它会在参考中找到100001.0     传感器中的索引3为100000.9924

bisect

def get_match(list_, el):
    import bisect

    i = bisect.bisect_left(list_, el)

    if i == len(list_):
        return i - 1
    elif list_[i] == el:
        return i
    elif i > 0:
        j = i - 1

        if list_[i] - el > el - list_[j]:
            return j
    return

reference = [99999.0, 100000.0, 100001.0]

sensor = [99999.8234, 99999.9723, 100000.00123, 100000.9924, 100001.02]

for el in reference:
    print(get_match(sensor,el))

None
None
3