【问题标题】:Python pandas time series interpolation and regularizationPython pandas 时间序列插值和正则化
【发布时间】:2015-08-12 08:16:53
【问题描述】:

我是第一次使用 Python Pandas。我有 csv 格式的 5 分钟滞后流量数据:

...
2015-01-04 08:29:05,271238
2015-01-04 08:34:05,329285
2015-01-04 08:39:05,-1
2015-01-04 08:44:05,260260
2015-01-04 08:49:05,263711
...

有几个问题:

  • 对于某些时间戳,缺少数据 (-1)
  • 缺少条目(也是连续 2/3 小时)
  • 观察的频率不完全是 5 分钟,但实际上偶尔会损失几秒钟

我想获得一个定期的时间序列,因此每(正好)5 分钟输入一次(并且没有缺失值)。我已经成功地使用以下代码对时间序列进行了插值,以使用此代码逼近 -1 值:

ts = pd.TimeSeries(values, index=timestamps)
ts.interpolate(method='cubic', downcast='infer')

如何对观察的频率进行插值和正则化?谢谢大家的帮助。

【问题讨论】:

    标签: python pandas time-series interpolation regularized


    【解决方案1】:

    -1s 更改为 NaN:

    ts[ts==-1] = np.nan
    

    然后对数据进行重新采样,使其具有 5 分钟的频率。

    ts = ts.resample('5T')
    

    请注意,默认情况下,如果两个测量值在同一个 5 分钟内,resample 会将这些值一起平均。

    最后,您可以根据时间对时间序列进行线性插值:

    ts = ts.interpolate(method='time')
    

    由于您的数据看起来已经具有大约 5 分钟的频率,因此您 可能需要以较短的频率重新采样,因此三次或样条插值 可以平滑曲线:

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    
    values = [271238, 329285, -1, 260260, 263711]
    timestamps = pd.to_datetime(['2015-01-04 08:29:05',
                                 '2015-01-04 08:34:05',
                                 '2015-01-04 08:39:05',
                                 '2015-01-04 08:44:05',
                                 '2015-01-04 08:49:05'])
    
    ts = pd.Series(values, index=timestamps)
    ts[ts==-1] = np.nan
    ts = ts.resample('T').mean()
    
    ts.interpolate(method='spline', order=3).plot()
    ts.interpolate(method='time').plot()
    lines, labels = plt.gca().get_legend_handles_labels()
    labels = ['spline', 'time']
    plt.legend(lines, labels, loc='best')
    plt.show()
    

    【讨论】:

    • 谢谢它完美的工作!有一种方法可以改为先将常规的 5 分钟时间戳添加到以 nan 作为值的系列中,然后用 3 阶样条线对它们进行插值?
    • 重采样在之前完成并且独立于插值。您不必进行线性插值。只需从labels 中删除行ts.interpolate(method='time').plot() 和关联的time。然后上面的代码单独使用 3 阶样条对数据进行插值。
    • how='mean' 告诉resample 如果多行在同一时期内,如何聚合 值(在这种情况下,T 表示时期频率为 1 分钟长.)
    • @DaveX:当然可以。而不是resample-ing 系列,使用reindex 添加具有NaN 值的新行。然后调用Series.interpolate(method='time') 将用插值填充缺失值。
    • 或者你可以使用combine_first作为HYRY shows here。 (在我看来,combine_first 可能是更好的解决方案,因为您不必像使用 reindex 那样将旧索引与新索引联合起来......)
    猜你喜欢
    • 2014-10-03
    • 2018-02-02
    • 2019-10-10
    • 2017-03-31
    • 2017-06-03
    • 2021-12-09
    • 1970-01-01
    • 2021-02-25
    • 2018-04-01
    相关资源
    最近更新 更多