【发布时间】:2019-03-30 17:14:41
【问题描述】:
我有一个看起来像这样的数据框:
|-----------------------------------------------------|
| | category | pct_formation |
|-----------------------------------------------------|
|ts_timestamp | | |
|-----------------------------------------------------|
|2018-10-22 10:13:44.043 | in_petr | 37.07 |
|2018-10-22 10:17:09.527 | in_petr | 36.97 |
|2018-10-22 10:17:43.977 | in_dsh | 36.95 |
|2018-10-22 10:17:43.963 | in_dsh | 36.96 |
|2018-10-22 10:17:09.527 | in_petr | 32.96 |
|2018-10-22 10:19:44.040 | out_petr | 36.89 |
|2018-10-23 10:19:44.043 | out_petr | 36.90 |
|2018-10-23 10:19:37.267 | sync | 33.91 |
|2018-10-23 10:19:44.057 | sync | 36.96 |
|2018-10-23 10:19:16.750 | out_petr | 36.88 |
|2018-10-23 10:20:03.160 | sync | 36.98 |
|2018-10-23 10:20:32.350 | sync | 37.00 |
|2018-10-23 10:23:03.150 | sync | 34.58 |
|2018-10-23 10:22:18.633 | in_dsh | 36.98 |
|2018-10-23 10:25:39.557 | in_dsh | 36.97 |
|-----------------------------------------------------|
数据包含每天在不同时间收集的各种类别的pct_formation 值(不规则频率、不均匀间隔)。
我想比较每天上午 9 点到 11 点之间 10 分钟滚动窗口中每个类别的平均 pct_formation 或一周内的平均值。
问题在于每个类别的数据并不总是在上午 9 点开始输入。对一些人来说,它从上午 9.10 开始,一些人从上午 9.15 开始,一些人从上午 10 点开始,依此类推。此外,数据不是定期出现的。如何获得上午 9 点到 11 点之间每天和每个类别的 10 分钟滚动平均值?
最初,我将ts_timestamp 列转换为索引:
df = df.set_index('ts_timestamp')
然后,我可以groupby 并像这样使用rolling():
df.groupby('category').rolling('10T').agg({'pct_formation': 'mean'})
但是,这不会显示定期的 10 分钟间隔,而是显示数据帧中的时间戳。
我意识到我需要像这样创建一个数据范围以用作索引:
pd.date_range(start=df.index.min().replace(hour=9, minute=0, second=0, microsecond=0),
end=df.index.max().replace(hour=11, minute=0, second=0, microsecond=0),
freq='10T')
#
# or should I use freq='1T' so that rolling() can do 10 minute intervals?
但是,如何将我的数据框与此范围对齐?如何平均范围之间出现的多个值?
我是处理时间序列数据的新手,希望能提供任何帮助。有什么不明白的欢迎追问。
【问题讨论】:
-
时间感知滚动是您正在寻找的:stackoverflow.com/a/41176540
标签: python pandas time-series pandas-groupby window-functions