【问题标题】:Python Smooth Time Series DataPython 平滑时间序列数据
【发布时间】:2021-09-07 13:50:38
【问题描述】:

我在 python 中有一些数据是 unixtime,值:

[(1301672429, 274), (1301672430, 302), (1301672431, 288)...]

时间不断地以一秒为单位。如何减少此数据,使时间戳为每秒,但该值是周围 10 个值的平均值?

更高级的滚动平均值也会很好,但这些数据是图表化的,因此主要是为了平滑图表。

跟进(TSQL Rolling Average of Time Groupings 得出的结论是尝试在 SQL 中执行此操作是一条痛苦之路)。

【问题讨论】:

    标签: python time-series


    【解决方案1】:

    使用http://www.scipy.org/Cookbook/SignalSmooth

    import numpy
    def smooth(x,window_len=11,window='hanning'):
            if x.ndim != 1:
                    raise ValueError, "smooth only accepts 1 dimension arrays."
            if x.size < window_len:
                    raise ValueError, "Input vector needs to be bigger than window size."
            if window_len<3:
                    return x
            if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
                    raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
            s=numpy.r_[2*x[0]-x[window_len-1::-1],x,2*x[-1]-x[-1:-window_len:-1]]
            if window == 'flat': #moving average
                    w=numpy.ones(window_len,'d')
            else:  
                    w=eval('numpy.'+window+'(window_len)')
            y=numpy.convolve(w/w.sum(),s,mode='same')
            return y[window_len:-window_len+1]
    

    我得到了似乎很好的结果(不是我理解数学):

       if form_results['smooth']:
                a = numpy.array([x[1] for x in results])
                smoothed = smooth(a,window_len=21)
                results = zip([x[0] for x in results], smoothed)
    

    【讨论】:

    • 这似乎是合理的。如果你想要平均值,那么你的窗口应该“平坦”。其他窗口协议对窗口中的数据点加权不同。
    • 如果使用 python 3,请确保将带有 ValueErrors 的行更改为:raise ValueError("smooth only accepts 1 dimension arrays.")
    【解决方案2】:

    我找到了 Savitzky-Golay 过滤器。它假设一个窗口并拟合多项式曲线和移位窗口。幸运的是它是在 scipy 中实现的。

    https://en.wikipedia.org/wiki/File:Lissage_sg3_anim.gif

    使用此代码:

    from scipy.signal import savgol_filter
    result = savgol_filter(value, 13, 5) # window size 13, polynomial order 5
    

    【讨论】:

      猜你喜欢
      • 2019-05-12
      • 2020-07-12
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-05
      • 2021-12-08
      相关资源
      最近更新 更多