gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:19 25 4
gpt4 key购买 nike

有类似的问题,但我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com