python-3.x - Python3如何将日期转换为每月周期,其中第一个周期是九月

标签 python-3.x pandas period

与一个财政年度从 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')

有办法调整每月频率吗?

最佳答案

我认为它没有实现,检查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

关于python-3.x - Python3如何将日期转换为每月周期,其中第一个周期是九月,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55931471/

相关文章:

c# - 如何检测 float 是否在 C# 中具有重复的小数扩展?

Python 的格式不适用于包含 JSON 的文本

python - 如何从(任意)连续概率分布进行模拟?

python - 如何使用 `np.where()` 比较数组而不是单个值

python - 我如何在 Python 中的一列中删除多个值

python - 用 Pandas 阅读excel专栏

python - 导入错误 : No module named bs4?

python - 将系列中的值映射到数据框中的所有元素

time - Tradingview Pine-Script : How to plot only the last x periods

java - JodaTime 打印周期错误?