moving-average - 重采样集中的移动平均值
问题描述
我有一个多年小时数据集的数据框 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()。
解决方案
我不是专家,会听从任何有更好答案的人。似乎有.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()
推荐阅读
- javascript - 使用 `fetch()` 在网页中显示纯文本
- python - 这个 Python 类中的“其他”变量是如何赋值的?
- apache - 如何在 AWS Elastic Container Service 上运行 Apache 的 Docker 容器中检索客户端 IP?
- python - 您如何最好使用 Python 将大型 SAV 文件(1k 列)放入 Postgres?
- vue.js - Vuetifyjs如何设置自定义RGBA颜色?
- vue.js - keep-alive 不缓存组件
- ruby-on-rails - Rails:关联计数的条件验证(仅在创建新关联时)
- python - 如何使用 Scrapy 下载图像
- flutter - 错误:“Widget”类型的值不能分配给“File”类型的变量
- java - 匹配和排除单词/字符串的正则表达式