【问题标题】:Summing time series with slight variance in timestamps对时间戳略有差异的时间序列求和
【发布时间】:2022-01-16 03:38:38
【问题描述】:

我想我有几个时间序列,如下所示,来自不同的“来源”:

       time     events
0      1000    1080000
1      2003    2122386
2      3007    3043985
3      4007    3872544
4      5007    4853763

这里,每 1000 毫秒采样一次单调递增计数事件。采样不是精确,因此大多数时间戳与其理想值相差几毫秒 - 例如,第二个点是 2003 年而不是 2000 年。

我想求和这些时间序列中的几个:它们都将在 ~1000 毫秒时采样,但可能不同意确切的毫秒。例如,另一个时间序列可能是:

       time     events
0      1000    1070000
1      2002    2122486
2      3006    3063985
3      4007    3872544
4      5009    4853763

我希望在最终结果方面合理。例如,与每个输入数据帧相同的行数,时间戳列与第一个相同,或输入时间的平均值。只要输入是平滑的,输出也应该是平滑的。

【问题讨论】:

    标签: pandas time-series


    【解决方案1】:

    我建议DataFrame.reindex() 使用最近的方法。示例:

    def combine_datasources(reference_df, extra_dfs, tolerance_ms=100):
        reindexed_df_list = [df.reindex(reference_df.index, method='nearest', tolerance=tolerance_ms) for df in extra_dfs]
        combined = pd.concat([reference_df, *reindexed_df_list])
        return combined.groupby(combined.index).sum()
    
    combine_datasources(df_a, [df_b])
    

    此代码更改 extra_dfs 列表中数据帧的索引以匹配参考数据帧的索引。然后,它将所有数据帧连接在一起。它使用 groupby 进行求和,这要求索引完全匹配才能工作。时间戳将与参考数据帧上的时间戳相同。

    请注意,如果您的数据来自参考数据框未涵盖的时间段,则该数据将被丢弃。

    这是您问题中数据集的输出:

           events
    time         
    1000  2150000
    2003  4244872
    3007  6107970
    4007  7745088
    5007  9707526
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-03
      • 2015-06-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2018-09-27
      • 2012-11-28
      • 1970-01-01
      相关资源
      最近更新 更多