在 Pandas 数据帧上使用 groupby 按财政年度进行分组

new*_*bie 5 group-by pandas

我有一个带有名为 DT 的datetime64列的数据框。是否可以使用groupby按财政年度从4月1日到3月31日进行分组?

例如,

    Date | PE_LOW 
    2010-04-01 | 15.44
    ...
    2011-03-31 | 16.8
    2011-04-02 | 17.
    ...
    2012-03-31 | 17.4
Run Code Online (Sandbox Code Playgroud)

对于上述数据,我想按 2010-2011 财年和 2011-2012 财年进行分组,而不创建额外的列。*

Jih*_*hun 3

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

DT.groupby(pd.DatetimeIndex(DT.Date).shift(-3,freq='m').year)
Run Code Online (Sandbox Code Playgroud)

或者如果用Date作为DT的索引,那就更简单了:

DT.groupby(DT.index.shift(-3,freq='m').year)
Run Code Online (Sandbox Code Playgroud)

但要注意将shift(-3,freq='m')日期移至月末;例如,4月8日至1月31日等。不管怎样,它很适合你的问题。