如何将每月数据转换为 pandas 的季度 [英] how to convert monthly data to quarterly in pandas
问题描述
我有月度数据。我想将其转换为1月份q1开始的3个月的期间。所以在下面的例子中,前3个月的汇总将转化为q2的开始(所需格式:1996q2)。并且由3个月值组合而产生的数据值是3列的平均值(平均值)。从概念上讲,并不复杂有谁知道如何做到这一点?潜在地,我可以通过循环来做很多努力,只是硬编码,但是我是大熊猫的新手,而且比野蛮力量更聪明。
I have monthly data. I want to convert it to "periods" of 3 months where q1 starts in January. So in the example below, the first 3 month aggregation would translate into start of q2 (desired format: 1996q2). And the data value that results from mushing together 3 monthly values is a mean (average) of 3 columns. Conceptually, not complicated. Does anyone know how to do it in one swoop? Potentially, I could do a lot of hard work through looping and just hardcode the hell out of it, but I am new to pandas and looking for something more clever than brute force.
非常感谢你。
1996-04 1996-05 1996-06 1996-07 .....
25 19 37 40
所以我在寻找:
1996q2 1996q3 1996q4 1997q1 1997q2 .....
avg avg avg ... ...
推荐答案
你可以使用 pd.PeriodIndex(...,freq ='Q')与 groupby(...,axis = 1):
In [63]: df
Out[63]:
1996-04 1996-05 2000-07 2000-08 2010-10 2010-11 2010-12
0 1 2 3 4 1 1 1
1 25 19 37 40 1 2 3
2 10 20 30 40 4 4 5
In [64]: df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1).mean()
Out[64]:
1996Q2 2000Q3 2010Q4
0 1.5 3.5 1.000000
1 22.0 38.5 2.000000
2 15.0 35.0 4.333333
这篇关于如何将每月数据转换为 pandas 的季度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!