我有一个数据帧,其中包含两个有用的列 1) 财政年度,2) 日期。我想添加一个显示财政季度的新列。
仅供参考 - 英国财政年度为4月1日至3月31
日我的数据如下所示:
fiscal year date
FY15/16 2015-11-01
FY14/15 2014-10-01
FY15/16 2016-02-01
我希望它看起来像这样:
fiscal year date Quarter
FY15/16 2015-11-01 q3
FY14/15 2014-10-01 q3
FY15/16 2016-02-01 q4
真的希望我把宿舍弄对了!
下面的代码有效,但我相信它会返回美国的财政季度,但我想要英国。
df['Quater'] = df['Date'].dt.quarter
import pandas as pd
df = pd.DataFrame({'date': ['2015-11-01', '2014-10-01', '2016-02-01'],
'fiscal year': ['FY15/16', 'FY14/15', 'FY15/16']})
df['Quarter'] = pd.PeriodIndex(df['date'], freq='Q-MAR').strftime('Q%q')
print(df)
收益 率
date fiscal year Quarter
0 2015-11-01 FY15/16 Q3
1 2014-10-01 FY14/15 Q3
2 2016-02-01 FY15/16 Q4
默认的季度频率Q
相当于 Q-DEC
。
In [60]: pd.PeriodIndex(df['date'], freq='Q')
Out[60]: PeriodIndex(['2015Q4', '2014Q4', '2016Q1'], dtype='int64', freq='Q-DEC')
Q-DEC
指定季度期间,其最后一个季度在 12 月的最后一天结束。 Q-MAR
指定季度期间,其最后一个季度在 3 月的最后一天结束。
In [86]: pd.PeriodIndex(df['date'], freq='Q-MAR')
Out[86]: PeriodIndex(['2016Q3', '2015Q3', '2016Q4'], dtype='int64', freq='Q-MAR')