gpt4 book ai didi

python - 如何将 pandas periodIndex 转换为特定的财政年度字符串格式?

转载 作者:行者123 更新时间:2023-11-30 22:03:34 26 4
gpt4 key购买 nike

我希望使用 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 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

Pandas 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

关于python - 如何将 pandas periodIndex 转换为特定的财政年度字符串格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53517827/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com