在python中寻找更好的方法使财政年度摆脱时间戳

在python中寻找更好的方法使财政年度摆脱时间戳,python,pandas,datetime,Python,Pandas,Datetime,我试图让财政年度从以下数据的“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_nume

我试图让财政年度从以下数据的“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

您可以在
季度
上使用
dt.qyear

df['RequestFY'] = df.RequestDate.dt.to_period('Q-SEP').dt.qyear
输出:

   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

您可以在
季度
上使用
dt.qyear

df['RequestFY'] = df.RequestDate.dt.to_period('Q-SEP').dt.qyear
输出:

   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

熊猫有一个
qyear

熊猫有一个
qyear

您没有指定会计年度开始的时间。假设它从7月1日开始运行到6月3日,请尝试

 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

您没有指定会计年度的开始时间。假设它从7月1日开始运行到6月3日,请尝试

 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