【问题标题】:Speeding up closest date merge in Pandas?加快 Pandas 中最近的日期合并?
【发布时间】:2017-04-30 03:21:22
【问题描述】:

我有两个包含时间列和值列的数据框,df1df2df1 是形状 [30000000 x 20]df2 是形状 [400 x 20]。我需要在df1 中创建一个新列,其中包含来自df2 的值,该值来自df2 中日期最近的行。我就是这样做的:

    df2= df2.sort_values(by='time_col').reset_index(drop=True)

    df1['closest'] = np.searchsorted(df2['time_col'].values, df1['time_col'].values)
    df1['new_values'] = [df2.loc[x, 'value_col'] for x in sales['closest']]

这可行,但需要很长时间。例如,对于 3000 万行的数据框,需要几个小时。

有没有更有效的方法来做到这一点?

【问题讨论】:

    标签: python performance pandas numpy merge


    【解决方案1】:

    老兄,只需使用 Pandas 19.0 和新的惊人的 merge as_of 进行时间序列

    http://pandas.pydata.org/pandas-docs/stable/merging.html#merging-asof

    【讨论】:

      猜你喜欢
      • 2014-08-28
      • 1970-01-01
      • 2013-06-06
      • 1970-01-01
      • 2017-08-26
      • 2020-06-30
      • 2018-08-15
      • 2020-01-09
      • 1970-01-01
      相关资源
      最近更新 更多