如何在熊猫中滚动"n"个月分区上的数据



我有一个数据集,如下所示:

month    year    value
1        2019    20
2        2019    13  
3        2019    10 
4        2019    20
5        2019    13  
6        2019    10 
7        2019    20
8        2019    13  
9        2019    10 
10        2019    20
11        2019    13  
12        2019    10 
1        2020    20
2        2020    13  
3        2020    10 
4        2020    40

请假设每个月和每年都发生多次,而且列要多得多。我想要创建的是在6个月的窗口中创建多个数据帧。我不想有聚合。分区的数据集应包括以下条件中的数据。请帮我照顾熊猫。我知道最简单的方法是手动使用条件来选择数据帧。但我想会有更有效的方法一次性完成这些操作。

month 1-6 year 2019
month 2-7 year 2019
month 3-8 year 2019
month 4-9 year 2019
month 5-10 year 2019
month 6-11 year 2019
month 7-12 year 2019
month 8-1 year 2019,2020
month 9-2 year 2019,2020
month 10-3 year 2019,2020
month 11-3 year 2019,2020

到目前为止我尝试了什么:

for i, j in zip(range(1,12), range(6,13)):
print(i,j)    # this is for 2019 

我可以把这个I和j插入几个月,并在2020年重复同样的操作。但有一种更好的方法可以很容易地创建数据帧列表。

使用datetime索引和pd.Grouper,您可以按照以下进行操作

df = pd.DataFrame(np.random.randn(12,3),  
index = pd.date_range(pd.Timestamp.now(), periods = 12), 
) 
df_grouped = df.groupby(pd.Grouper(freq = "6M"))
[df_grouped.get_group(x) for x in df_grouped.groups] 

最新更新