【问题标题】:Python3 How to convert date into monthly periods where the first period is SeptemberPython3如何将日期转换为第一个周期是九月的月度周期
【发布时间】:2019-09-19 17:41:50
【问题描述】:

与一个会计年度从 9 月开始的小组合作。我有一个包含一堆日期的数据框,我想计算一个月周期 = 9 月。

什么有效:

# 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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我认为'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)
    

    【讨论】:

      猜你喜欢
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多