【发布时间】:2019-03-14 19:58:02
【问题描述】:
我想从几个小时重新采样到半小时。我在示例中使用了.ffill(),但我也测试了.asfreq() 作为中间步骤。
目标是获得半小时的间隔,其中每小时值分布在上采样间隔中,我正在尝试为具有相同问题的任何范围找到通用解决方案。
import pandas as pd
index = pd.date_range('2018-10-10 00:00', '2018-10-10 02:00', freq='H')
hourly = pd.Series(range(10, len(index)+10), index=index)
half_hourly = hourly.resample('30min').ffill() / 2
hourly 系列看起来像:
2018-10-10 00:00:00 10
2018-10-10 01:00:00 11
2018-10-10 02:00:00 12
Freq: H, dtype: int64
还有half_hourly:
2018-10-10 00:00:00 5.0
2018-10-10 00:30:00 5.0
2018-10-10 01:00:00 5.5
2018-10-10 01:30:00 5.5
2018-10-10 02:00:00 6.0
Freq: 30T, dtype: float64
最后一个问题是没有行代表02:30:00
我想实现的目标是:
2018-10-10 00:00:00 5.0
2018-10-10 00:30:00 5.0
2018-10-10 01:00:00 5.5
2018-10-10 01:30:00 5.5
2018-10-10 02:00:00 6.0
2018-10-10 02:30:00 6.0
Freq: 30T, dtype: float64
我知道hourly 系列在 02:00 结束,因此没有理由期望 pandas 默认插入最后半小时。但是,在阅读了许多已弃用/旧的帖子、一些较新的帖子、documentation 和 cookbook 之后,我仍然无法找到直接的解决方案。
最后,我还测试了.mean() 的使用,但这并没有填满 NaNs. And interpolate() 并没有按我想要的按小时平均。
在这种情况下,我的.ffill() / 2 几乎可以将一小时到半小时分散,但这似乎是对我希望 pandas 已经提供更好解决方案的问题的破解。
提前致谢。
【问题讨论】:
标签: python pandas time-series date-range resampling