Python3如何将日期转换为第一个句点为9月的月度期间

问题描述 投票:2回答:2

与财政年度从9月份开始的团队合作。我有一个包含大量日期的数据框,我想计算9月份= 1的月度期。

什么有效:

# 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')

有没有办法调整每月的频率?

python-3.x pandas period
2个回答
2
投票

我认为它没有实现,请检查anchored offsets

可能的解决方案是减去或Index.shift 8换班8个月:

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

1
投票

我认为'M-Aug'不适用于月份,所以你可以通过使用np.where进行一点调整,数据来自Jez

np.where(df['Hours_Date'].dt.month-8<=0,df['Hours_Date'].dt.month+4,df['Hours_Date'].dt.month-8)
Out[271]: array([ 8,  9, 10, 11, 12,  1,  2,  3,  4,  5], dtype=int64)
© www.soinside.com 2019 - 2024. All rights reserved.