使用pandas数据框上的groupby按财年分组 [英] using groupby on pandas dataframe to group by financial year

查看:552
本文介绍了使用pandas数据框上的groupby按财年分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为DT的 datetime64 列的 dataframe 。从4月1日到3月31日的财政年度可以使用groupby进行分组吗?

I have a dataframe with a datetime64 column called DT. Is it possible to use groupby to group by financial year from April 1 to March 31?

例如,

For example,

    Date | PE_LOW 
    2010-04-01 | 15.44
    ...
    2011-03-31 | 16.8
    2011-04-02 | 17.
    ...
    2012-03-31 | 17.4

对于上述数据,我希望按2010-2011财年和2011财年 - 2012年,没有创建额外的列。*

For the above data, I want to group by Fiscal Year 2010-2011 and Fiscal Year 2011-2012 without creating an extra column.*

推荐答案

使用pandas.DatetimeIndex,这非常简单: b

With pandas.DatetimeIndex, that is very simple:

DT.groupby(pd.DatetimeIndex(DT.Date).shift(-3,freq='m').year)

或者如果您使用Date作为DT的索引,则更简单:

Or if you use Date as an index of DT, it is even simpler:

DT.groupby(DT.index.shift(-3,freq='m').year)

但要注意 shift(-3,freq ='m')将日期转移到月末;例如,4月8日至1月31日等。无论如何,它适合你的问题。

But beware that shift(-3,freq='m') shifts date to ends of months; for example, 8 Apr to 31 Jan and so on. Anyway, it fits your problem well.

这篇关于使用pandas数据框上的groupby按财年分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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