gpt4 book ai didi

python - pandas 滚动分组时间序列数据

转载 作者:行者123 更新时间:2023-12-01 03:22:31 25 4
gpt4 key购买 nike

我有found a few相关问题,但似乎没有一个能解决问题。我想要一个与 this 类似的实现但使用 pandas 数据框结构。下面我创建了 2016 年全年的示例数据,共有 366 行。

import pandas as pd
import numpy as np
dates=pd.date_range('2016-01-01','2016-12-31')
random_data=np.random.randn(len(dates))
data=pd.DataFrame(random_data,index=dates,columns=['Test'])

我想使用 groupby 每 2 天获取接下来 5 天的数据。正常的 groupby 没有重叠的时间帧;放入 2 天的分组将为我提供 183 (366/2) 个具有两天数据的组。如果分组时间为 5 天,则大约有 74 (366/5) 个组,每个组有 5 天。我想要 183 个小组,每个小组有五天的时间。

如果不清楚,请提前抱歉。这是我想要的:

            Test
2016-02-08 1.073696
2016-02-09 1.169865
2016-02-10 1.421454
2016-02-11 -0.576036
2016-02-12 -1.066921

Test
2016-02-10 1.421454
2016-02-11 -0.576036
2016-02-12 -1.066921
2016-02-13 2.639681
2016-02-14 -0.261616

这就是我通过 data.groupby(pd.TimeGrouper('2d')) 得到的结果

            Test
2016-02-08 1.073696
2016-02-09 1.169865
Test
2016-02-10 1.421454
2016-02-11 -0.576036
Test
2016-02-12 -1.066921
2016-02-13 2.639681

这就是我通过 data.groupby(pd.TimeGrouper('5d')) 得到的结果

            Test
2016-02-08 0.898029
2016-02-09 -0.905950
2016-02-10 -0.202483
2016-02-11 1.073696
2016-02-12 1.169865
Test
2016-02-13 1.421454
2016-02-14 -0.576036
2016-02-15 -1.066921
2016-02-16 2.639681
2016-02-17 -0.261616

最佳答案

如果日期是正常序列,如示例数据所示,相差一天,则可以使用索引来选取行。 从每两行开始,每次选择五行:

[data.iloc[i:(i+5)] for i in range(0, len(data), 2)]

#[ Test
# 2016-01-01 0.450173
# 2016-01-02 -0.496819
# 2016-01-03 0.270781
# 2016-01-04 -0.207634
# 2016-01-05 1.032061,
# Test
# 2016-01-03 0.270781
# 2016-01-04 -0.207634
# 2016-01-05 1.032061
# 2016-01-06 -0.470462
# 2016-01-07 -1.077634, ...]

关于python - pandas 滚动分组时间序列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41798763/

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