Python 如何将索引转换为特定的财政年度字符串格式?
我希望使用periodIndex系列,并创建一个新系列,以这种格式“yyyy/yy”显示当前财政年度。例如,以英国财政年度为例->01/04至31/03Python 如何将索引转换为特定的财政年度字符串格式?,python,pandas,date,Python,Pandas,Date,我希望使用periodIndex系列,并创建一个新系列,以这种格式“yyyy/yy”显示当前财政年度。例如,以英国财政年度为例->01/04至31/03 df = pd.DataFrame({ 'dates' : pd.date_range('3/01/11', periods= 3, freq='M'), 'amounts': np.random.randint(10, 100_000, 3) }) df dates amo
df = pd.DataFrame({
'dates' : pd.date_range('3/01/11', periods= 3, freq='M'),
'amounts': np.random.randint(10, 100_000, 3)
})
df
dates amounts
0 2011-03-31 28618
1 2011-04-30 517
2 2011-05-31 69892
我期望的结果在下面的系列fy
中给出。我使用了pd.PeriodIndex(df['dates',freq='Q-MAR').strftime(“%y”)
。到目前为止,无法实现以下结果
dates amounts fy
0 2011-03-31 28618 2010/11
1 2011-04-30 517 2011/12
2 2011-05-31 69892 2011/12
先谢谢你
numpy 1.15.4
熊猫0.23.4
python 3.7.1您似乎需要:
df = pd.DataFrame({
'dates' : pd.date_range('3/01/11', periods= 20, freq='2M'),
'amounts': np.random.randint(10, 100_000, 20)
})
p = pd.PeriodIndex(df['dates'], freq = 'Q-MAR')
df['fy'] = [(a - b).strftime('%Y/')+(a - b + 4).strftime('%y') for a, b in zip(p, p.quarter)]
替代解决方案:
df['fy1'] = [f'{x}/{str(x + 1)[2:]}' for x in (df.dates - pd.offsets.QuarterEnd()).dt.year]
print (df)
dates amounts fy
0 2011-03-31 30629 2010/11
1 2011-05-31 66159 2011/12
2 2011-07-31 48821 2011/12
3 2011-09-30 92771 2011/12
4 2011-11-30 55348 2011/12
5 2012-01-31 10745 2011/12
6 2012-03-31 91046 2011/12
7 2012-05-31 32632 2012/13
8 2012-07-31 77657 2012/13
9 2012-09-30 95364 2012/13
10 2012-11-30 78078 2012/13
11 2013-01-31 44535 2012/13
12 2013-03-31 89158 2012/13
13 2013-05-31 94263 2013/14
14 2013-07-31 99759 2013/14
15 2013-09-30 59057 2013/14
16 2013-11-30 38363 2013/14
17 2014-01-31 98069 2013/14
18 2014-03-31 44797 2013/14
19 2014-05-31 87895 2014/15
在财政年度试试这个
pd.PeriodIndex(df['dates'], freq = 'Q-MAR').strftime('%F')
参考:
谢谢您的上述建议。我不相信上面的代码行会产生结果。检索的三个值
fy
将默认为dates
中显示的同一年,忽略PeriodIndex()
。i、 e.['2011/11'、'2011/11'、'2011/11']
对不起,忘记给您的手机贴标签了username@Francisco-正在努力。。。有一件事-2011-03-31
不是2011/12
?谢谢。2011-03-31是2010/11财政年度的最后一天。2011-04-01将是2011/12财年的第一天。我注意到PeriodIndex总是以所需的符号正确播放下一年。ie 2011-04-01将是2012Q1
和2011-03-312011Q4
。完美。谢谢你的回答!明亮的