【问题标题】:Finding closest timestamp between dataframe columns查找数据框列之间最近的时间戳
【发布时间】:2020-11-06 08:23:48
【问题描述】:

我有两个数据框

import numpy as np
import pandas as pd

test1 = pd.date_range(start='1/1/2018', end='1/10/2018')
test1 = pd.DataFrame(test1)
test1.rename(columns = {list(test1)[0]: 'time'}, inplace = True)


test2 = pd.date_range(start='1/5/2018', end='1/20/2018')
test2 = pd.DataFrame(test2)
test2.rename(columns = {list(test2)[0]: 'time'}, inplace = True)

现在我在第一个数据框中创建列

test1['values'] = np.zeros(10)

我想填写此列,每个日期旁边应该有与第二个数据框最接近的日期的索引。我希望它看起来像这样:

0 2018-01-01   0
1 2018-01-02   0
2 2018-01-03   0
3 2018-01-04   0
4 2018-01-05   0
5 2018-01-06   1
6 2018-01-07   2
7 2018-01-08   3

当然我的真实数据不是均匀分布的,有分秒,但思路是一样的。我使用以下代码:

def nearest(items, pivot):
    return min(items, key=lambda x: abs(x - pivot))

for k in range(10):
    a = nearest(test2['time'], test1['time'][k]) ### find nearest timestamp from second dataframe

    b = test2.index[test2['time'] == a].tolist()[0] ### identify the index of this timestamp

    test1['value'][k] = b   ### assign this value to the cell

这段代码在大型数据集上速度很慢,如何提高效率?

附:就像在这些人工示例中一样,我的真实数据中的时间戳被排序和增加。

【问题讨论】:

    标签: python pandas sorting datetime


    【解决方案1】:

    您可以在一行中使用 numpy 的 argmin

    test1['values'] = test1['time'].apply(lambda t: np.argmin(np.absolute(test2['time'] - t)))
    

    请注意,应用 lambda 函数本质上也是一个循环。检查这是否满足您的性能要求。


    您还可以利用时间戳已排序并且每个时间戳之间的时间增量是恒定的这一事实(如果我理解正确的话)。以天为单位计算偏移量并得出索引向量,例如如下:

    offset = (test1['time'] - test2['time']).iloc[0].days
    if offset < 0: # test1 time starts before test2 time, prepend zeros:
        offset = abs(offset)
        idx = np.append(np.zeros(offset), np.arange(len(test1['time'])-offset)).astype(int)
    else: # test1 time starts after or with test2 time, use arange right away:
        idx = np.arange(offset, offset+len(test1['time']))
        
    test1['values'] = idx
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-01
      • 1970-01-01
      • 2020-05-08
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      相关资源
      最近更新 更多