寻找一种从python的时间戳中删除会计年度的更好方法

问题描述 投票:1回答:3

我正在尝试将以下会计年度从“ 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
python pandas datetime
3个回答
0
投票
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

0
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.