从几个月计算季度 [英] calculate quarters from months
本文介绍了从几个月计算季度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据列,按月份列出数量
I have a data frame with a number of columns by month
c1 c2 yyyy-01 yyyy-02 yyyy-03 yyyy-04 yyyy-05 yyyy-06 ...
a A 1 1 3 2 2 3
b B 2 3 4 4 2 1
...
有大约15年的数据
我需要将其转换为季度
ie
... There are about 15 years of data I need to transform it to quarters ie
c1 c2 yyyy-q1 yyyy-q2 ...
a A 5 7
b B 9 7
...
等等。
任何帮助?似乎地图可能会这样做,但是我不太熟练地图或羊羔。
and so forth. Any help? It seems a map might do it, but I am not well versed in map or lambdas.
推荐答案
- 使用
pd.to_datetime()
和to_period()
函数来创建每年季度的组变量; / li>
- 您可以将轴参数传递给
groupby()
函数,以按列分组数据帧,在这种情况下是列索引。
- Use
pd.to_datetime()
andto_period()
functions to create a group variable of quarters for each year; - You can pass an axis parameter to the
groupby()
function to group your data frame by columns, in this case the column index.
所以,你可以尝试:
df.set_index(['c1', 'c2'], inplace=True)
df
df.groupby(pd.to_datetime(df.columns).to_period("Q"), axis=1).sum().reset_index()
这篇关于从几个月计算季度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文