本文介绍了Python3如何将日期转换为第一个时期为9月的每月时期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
与一个从9月开始的会计年度的小组一起工作.我有一个带有一堆日期的数据框,我想计算一个9月= 1的月度周期.
Working with a group that has a Fiscal Year that starts in September. I have a dataframe with a bunch of dates that I want to calculate a monthly period that = 1 in September.
有效方法:
# Convert date column to datetime format
df['Hours_Date'] = pd.to_datetime(df['Hours_Date'])
# First quarter starts in September - Yes!
df['Quarter'] = pd.PeriodIndex(df['Hours_Date'], freq='Q-Aug').strftime('Q%q')
什么不起作用:
# Gives me monthly periods starting in January. Don't want.
df['Period'] = pd.PeriodIndex(df['Hours_Date'], freq='M').strftime('%m')
# Gives me an error
df['Period'] = pd.PeriodIndex(df['Hours_Date'], freq='M-Aug').strftime('%m')
有没有一种可以调整每月频率的方法?
Is there a way to adjust the monthly frequency?
推荐答案
我认为它尚未实现,请检查锚定的偏移量.
I think it is not implemented, check anchored offsets.
Possible solution is subtract or Index.shift
8
for shift by 8 months:
rng = pd.date_range('2017-04-03', periods=10, freq='m')
df = pd.DataFrame({'Hours_Date': rng})
df['Period'] = (pd.PeriodIndex(df['Hours_Date'], freq='M') - 8).strftime('%m')
或者:
df['Period'] = pd.PeriodIndex(df['Hours_Date'], freq='M').shift(-8).strftime('%m')
print (df)
Hours_Date Period
0 2017-04-30 08
1 2017-05-31 09
2 2017-06-30 10
3 2017-07-31 11
4 2017-08-31 12
5 2017-09-30 01
6 2017-10-31 02
7 2017-11-30 03
8 2017-12-31 04
9 2018-01-31 05
这篇关于Python3如何将日期转换为第一个时期为9月的每月时期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!