python - Pandas 在日期时间多索引框架上滚动

标签 python pandas

有类似的问题,但我的 datetime 对象空间很大,没有顺序,例如它们是时间上的随机时间戳。基本上我需要的是使用 rolling() 但在记住组(第一个索引)的同时将其滚动到第二个索引。

有一个非常相似的 GitHub 问题,您可能也想参与其中: https://github.com/pandas-dev/pandas/issues/15584

重现代码:

import pandas as pd
data = {
    'id': ['A','A','A','B'],
    'time': pd.to_datetime(['2018-01-04 08:13:51.181','2018-01-04 08:13:55.181','2018-01-04 09:13:51.181', '2018-01-04 08:13:51.183']),
    'colA': [4,3,2,1],
    '30min_rolling_output': [4,7,2,1],
    '1day_rolling_output': [4,7,9,1]
}
test_df = pd.DataFrame(data=data).set_index(['id', 'time'])

所需的输出假设为 30m1h 参数。

可视化:

                            colA  30min_rolling_output  1day_rolling_output
id date                                                          
A  2018-01-04 08:13:51.181     4                     4                    4
   2018-01-04 08:13:55.181     3                     7                    7
   2018-01-04 09:13:51.181     2                     2                    9
B  2018-01-04 08:13:51.183     1                     1                    1

最佳答案

从索引中删除 id,留下一个 DatetimeIndex,然后您可以滚动它。

test_df['30min'] = test_df.reset_index(level=0).groupby('id').colA.rolling('30min').sum()
test_df['1day'] = test_df.reset_index(level=0).groupby('id').colA.rolling('1d').sum()

输出

                            colA  30min  1day
id time                                      
A  2018-01-04 08:13:51.181     4    4.0   4.0
   2018-01-04 08:13:55.181     3    7.0   7.0
   2018-01-04 09:13:51.181     2    2.0   9.0
B  2018-01-04 08:13:51.183     1    1.0   1.0

关于python - Pandas 在日期时间多索引框架上滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52558461/

相关文章:

python - 如何设置可选参数?

python - 转换 pandas datetime 中的混合日期类型

python - Pandas 从上一行中减去另一列中的值

python - 通过分组分隔列中的数据

python - 按列将两个 Pandas 系列附加到数据框

python - 无法在 iPython 笔记本中与文森特一起绘制世界地图

python - 将多个字符串列转换为整数列表

python - 关于 np.all 和 axis 的用法

python - 转换 pandas 数据框中的日期格式

python - ./manage.py runserver 使用 https