Pandas 在 DateTime 多索引框架上滚动

use*_*178 5 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'])
Run Code Online (Sandbox Code Playgroud)

所需的输出是假设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
Run Code Online (Sandbox Code Playgroud)

ALo*_*llz 5

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()
Run Code Online (Sandbox Code Playgroud)

输出

                            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
Run Code Online (Sandbox Code Playgroud)