![](/img/trans.png)
[英]python pandas: get fiscal quarter from fiscal year and month (for UK)
[英]Looking for better way to get the fiscal year out of the time stamp in python
我试图让会计年度脱离数据之后的“RequestDate”列。
我使用了以下有效但正在寻找更好的方法来执行此操作的代码:
import pandas as pd
import numpy as np
import datetime as datetime
df = pd.read_csv('test.csv')
df['CalendarYear'] = df['RequestDate'].dt.year
df['Month'] = df.RequestDate.dt.month
c = pd.to_numeric(df['CalendarYear'])
df['RequestFY'] = np.where(df['Month'] >= 10, c+1, c)
df.drop(['Month', 'CalendarYear'], axis=1, inplace=True)
Before:
Index RequestDate
0 2019-05-01
1 2018-08-02
2 2016-01-01
3 2015-03-01
4 2005-02-01
5 2005-10-01
After:
Index RequestDate RequestFY
0 2019-05-01 2019
1 2018-08-02 2018
2 2016-01-01 2016
3 2015-03-01 2015
4 2005-02-01 2005
5 2005-10-01 2006
您可以在Quarter
上使用dt.qyear
:
df['RequestFY'] = df.RequestDate.dt.to_period('Q-SEP').dt.qyear
Output:
Index RequestDate RequestFY
0 0 2019-05-01 2019
1 1 2018-08-02 2018
2 2 2016-01-01 2016
3 3 2015-03-01 2015
4 4 2005-02-01 2005
5 5 2005-10-01 2006
Pandas 具有qyear
功能。
您没有指定会计年度的开始时间。 假设从July 1st
开始,一直持续到June 3oth
,请尝试;
df['RequestFY']= pd.to_datetime(df['RequestDate']).apply(pd.Period, freq='A-JUL')#Fiscal year running from July to June
Index RequestDate RequestFY
0 0 2019-05-01 2019
1 1 2018-08-02 2019
2 2 2016-01-01 2016
3 3 2015-03-01 2015
4 4 2005-02-01 2005
5 5 2005-10-01 2006
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.