假设我有一个pd.DataFrame
,其中索引由pd.DateTimeIndex
给出。
现在我想按月份分组成对,即获取所有成对数据。也就是说,我想要一个组,其中包含(日期在(一月、二月)之间
),然后是(日期在(二月、三月)之间
)等等。自然的方式应该是pd.TimeGrouper
,但我找不到使其工作的方法。
这是一个样本数据集。请注意每个月有多个观测值(数字随时间变化而异),因此pd.rolling()
和pd.rolling_apply()
似乎不是有效的替代方案:
year month cpsidp
date
2000-01-01 2000 1 19981003169301
2000-02-01 2000 2 20000200000101
2000-02-01 2000 2 20000200000102
2000-02-01 2000 2 20000200000103
2000-02-01 2000 2 20000200000104
2000-02-01 2000 2 20000200000105
2000-03-01 2000 3 19981203124802
2000-04-01 2000 4 20000400000101
2000-05-01 2000 5 19990200854301
2000-06-01 2000 6 19990300018604
2000-07-01 2000 7 20000400000101
2000-08-01 2000 8 19990502683801
2000-09-01 2000 9 19990600006901
2000-10-01 2000 10 19990700006501
2000-11-01 2000 11 19990800083001
2000-12-01 2000 12 19991100000301
2001-01-01 2001 1 19991100000301
2001-02-01 2001 2 19991100002701
2001-03-01 2001 3 20000205949101
2001-04-01 2001 4 20010100107701
2001-05-01 2001 5 20000204516501
2001-06-01 2001 6 20000300112801
2001-07-01 2001 7 20000400000101
2001-08-01 2001 8 20000505217801
以下是我用非pandas和非花哨的方式创建组的方法:
dates = df.index.unique()
for i, date in enumerate(dates):
if i == len(dates) - 1:
# last group: no next-group, break
break
date1, date2 = date, dates[i+1]
group = pd.concat((df.loc[date1], df.loc[date2]), axis=0)
print(group)
df.groupby(pd.TimeGrouper(freq='2M')).mean()
这样的东西不是你需要的吗? - MaxU - stand with Ukraine(一月,二月)
和(三月,四月)
- 而不是(一月,二月)
,(二月,三月)
,(三月,四月)
。 - FooBar