【问题标题】:Pandas: De-seasonalizing time-series dataPandas:去季节化时间序列数据
【发布时间】:2014-08-20 00:37:48
【问题描述】:

我有以下数据框df

[输出]:

                     VOL
2011-04-01 09:30:00  11297
2011-04-01 09:30:10  6526
2011-04-01 09:30:20  14021
2011-04-01 09:30:30  19472
2011-04-01 09:30:40  7602
...
2011-04-29 15:59:30  79855
2011-04-29 15:59:40  83050
2011-04-29 15:59:50  602014

df 包含连续 22 天每 10 秒的体积观察。我想通过将每个观察值除以它们各自的 5 分钟时间间隔的平均量来对我的时间序列进行去季节性化。为此,我需要在 22 天内每 5 分钟计算一次成交量的时间序列平均值。所以我会在每 5 分钟 9:30:00 - 9:35:00; 9:35:00 - 9:40:00; 9:40:00 - 9:45:00 ... 直到 16:00:00 得到一个时间序列的平均值。间隔9:30:00 - 9:35:00 的平均值是该时间间隔在所有 22 天内的平均交易量(即,9:30:00 到 9:35:00 之间的平均值是 9:30:00 到 9 之间的总交易量:35:00 on (day 1 + day 2 + day 3 ... day 22) / 22 . 这有意义吗?)。然后,我会将df 中位于9:30:00 - 9:35:00 之间的每个观察值除以该时间间隔的平均值。

Python/Pandas 中是否有一个包可以做到这一点?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    编辑答案:

    date_times = pd.date_range(datetime.datetime(2011, 4, 1, 9, 30),
                               datetime.datetime(2011, 4, 16, 0, 0),
                               freq='10s')
    VOL = np.random.sample(date_times.size) * 10000.0
    
    df = pd.DataFrame(data={'VOL': VOL,'time':date_times}, index=date_times)
    df['h'] = df.index.hour
    df['m'] = df.index.minute
    df1 = df.resample('5Min', how={'VOL': np.mean})
    times = pd.to_datetime(df1.index)
    df2 = df1.groupby([times.hour,times.minute]).VOL.mean().reset_index()
    df2.columns = ['h','m','VOL']
    df.merge(df2,on=['h','m'])
    df_norm = df.merge(df2,on=['h','m'])
    df_norm['norm'] = df_norm['VOL_x']/df_norm['VOL_y']
    

    ** 旧答案(暂时保留)

    使用重采样功能

    df.resample('5Min', how={'VOL': np.mean})
    

    例如:

    date_times = pd.date_range(datetime.datetime(2011, 4, 1, 9, 30),
                               datetime.datetime(2011, 4, 16, 0, 0),
                               freq='10s')
    VOL = np.random.sample(date_times.size) * 10000.0
    
    df = pd.DataFrame(data={'VOL': VOL}, index=date_times)
    df.resample('5Min', how={'VOL': np.mean})
    

    【讨论】:

    • 不,这只是整个样本每 5 分钟的连续平均值。我需要整个时间序列中每 5 分钟间隔的平均值。因此,9:30:00 到 9:35:00 之间的平均值是(第 1 天 + 第 2 天 + 第 3 天 ... 第 22 天)/ 22 的 9:30:00 到 9:35:00 之间的总交易量。这有意义吗?感谢您的尝试
    • 我认为有问题...... df_norm 中的行数应该与 df 中的行数相同
    • 我认为缺少的是对于 df['h'] = df.index.hour 和 df['m'] = df.index.minute 我们需要最接近的小时和分钟第 5 分钟间隔
    猜你喜欢
    • 2017-03-11
    • 2012-10-25
    • 2020-09-21
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2017-12-29
    • 2015-11-24
    • 1970-01-01
    相关资源
    最近更新 更多