首页 > 解决方案 > 重采样集中的移动平均值

问题描述

我有一个多年小时数据集的数据框 df,并且想要计算每天8 小时的移动平均值。感谢 PatrickT 的有益讨论,我尝试了以下方法:

import pandas as pd
import random

numbers = [random.randint(10, 80) for i in range(48)]
datetimes = pd.date_range(start="2021-08-01 00:00:00", end="2021-08-2 23:00:00", freq='1h')
df = pd.DataFrame (data = numbers, index = datetimes, columns = ['var'])
df.resample('D')['var'].apply(lambda x: x.rolling(8).mean())

它奏效了!

我最初的问题是我使用了“df.resample('D')['var'].rolling(8).mean()”,这给了我一个错误“索引 2 超出轴 0 的范围,大小为 2 ”。受到与 PatrickT 讨论并结合互联网搜索的启发,我使用了 apply() 并且它奏效了!虽然我仍然不知道为什么 resample() 不能跟随 rolling()。

标签: moving-averageresampling

解决方案


我不是专家,会听从任何有更好答案的人。似乎有.pad()帮助:

import pandas as pd
import random

datetimes = pd.date_range(start="2019-08-01 00:00:00", end="2021-08-2 23:00:00", freq='1h')
numbers = [random.randint(10, 80) for i in range(len(datetimes))]
df = pd.DataFrame ({'data': numbers, 'index': datetimes})
df.head()

df.set_index('index').resample('D').pad().rolling(window=8).mean()

推荐阅读