如何在 pandas 中将月度数据转换为季度数据 [英] how to convert monthly data to quarterly in pandas

查看:58
本文介绍了如何在 pandas 中将月度数据转换为季度数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有月度数据.我想将其转换为 3 个月的周期",其中 q1 于 1 月开始.因此,在下面的示例中,前 3 个月的聚合将转换为 q2 的开始(所需格式:1996q2).将 3 个月值混合在一起得到的数据值是 3 列的平均值(平均值).从概念上讲,并不复杂.有谁知道如何一举完成?潜在地,我可以通过循环做很多艰苦的工作,只是硬编码它的地狱,但我是熊猫的新手,正在寻找比蛮力更聪明的东西.

<前>1996-04 1996-05 1996-06 1996-07 .....25 19 37 40

所以我在寻找:

<前>1996q2 1996q3 1996q4 1997q1 1997q2 .....平均 平均 平均 ......

解决方案

你可以使用 pd.PeriodIndex(..., freq='Q')groupby(...,axis=1):

在 [63]: df出[63]:1996-04 1996-05 2000-07 2000-08 2010-10 2010-11 2010-120 1 2 3 4 1 1 11 25 19 37 40 1 2 32 10 20 30 40 4 4 5在 [64]: df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1).mean()出[64]:1996Q2 2000Q3 2010Q40 1.5 3.5 1.0000001 22.0 38.5 2.0000002 15.0 35.0 4.333333

<小时>

UPDATE:将结果 DF 中的列作为字符串而不是 period dtype:

In [66]: res = (df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1).意思是().rename(columns=lambda c: str(c).lower()))在[67]:res出[67]:1996q2 2000q3 2010q40 1.5 3.5 1.0000001 22.0 38.5 2.0000002 15.0 35.0 4.333333在 [68]: res.columns.dtype输出 [68]: dtype('O')

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

So I am looking for:

1996q2  1996q3   1996q4  1997q1  1997q2 .....
 avg      avg      avg     ...     ...

解决方案

you can use pd.PeriodIndex(..., freq='Q') in conjunction with 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


UPDATE: to get columns in a resulting DF as strings intead of period dtype:

In [66]: res = (df.groupby(pd.PeriodIndex(df.columns, freq='Q'), axis=1)
                  .mean()
                  .rename(columns=lambda c: str(c).lower()))

In [67]: res
Out[67]:
   1996q2  2000q3    2010q4
0     1.5     3.5  1.000000
1    22.0    38.5  2.000000
2    15.0    35.0  4.333333

In [68]: res.columns.dtype
Out[68]: dtype('O')

这篇关于如何在 pandas 中将月度数据转换为季度数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆