python - 寻找更好的方法来让会计年度脱离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
解决方案
您没有指定会计年度的开始时间。说它开始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
推荐阅读
- rest - 向 LinkedIn REST API 提供一系列 URN?
- bootstrap-modal - 当我更喜欢“模态”时,Div 没有作为链接打开
- html - CSS 图像和 SVG 之间的区别
- javascript - 来自变量的Angular ngFor轮播
- jquery - 在 jquery 中将表格转换为 Excel
- c# - IIS 抛出错误:HTTP 错误 500.19 - 内部服务器错误
- c++ - 从基指针的源容器构造派生指针的容器
- python - 在 FLASK 中的表单的同一页面上显示数据
- javascript - 如何在控制器的会话中将值传递给视图刀片 PHP laravel?
- r - 使用 tidyselect 函数使用 dplyr 重命名列名