【问题标题】:Pandas datetime function to get the date at the end of the quarterPandas datetime 函数获取季度末的日期
【发布时间】:2020-06-18 18:40:38
【问题描述】:

我有一个包含年季度列df.period 的数据框 我想用这段代码将该列转换为DatetimeIndex

# path is my filepath
df = pd.read_excel(path, skiprows =[1,2,3,4]) # unread first four rows
idx = pd.to_datetime(df.period)
df = df.set_index(pd.DatetimeIndex(idx))

代码对我很有效;但是,它会在PeriodIdx 返回每​​个季度的第一个日期。

+------------+--------+
| PeriodIdx  | Period |
+------------+--------+
| 2000-01-01 | 2000Q1 |
| 2000-04-01 | 2000Q2 |
| ...        | ...    |
+------------+--------+

但我的目标输出是获取每个季度的结束日期,如下所示。

+------------+--------+
| PeriodIdx  | Period |
+------------+--------+
| 2000-03-31 | 2000Q1 |
| 2000-06-30 | 2000Q2 |
| ...        | ...    |
+------------+--------+

参考 R Forcing end of quarter date for as.Date(as.yearqtr()) 中的解决方案,有没有针对季度最后一个日期的 Pandas 函数?

【问题讨论】:

    标签: python pandas dataframe datetime


    【解决方案1】:

    一种解决方法是添加偏移量:

    idx = pd.DatetimeIndex(pd.to_datetime(df.period) + pd.offsets.MonthEnd(3),
                           name='PeriodIdx')
    
    df.set_index(idx)
    

    输出:

                Period
    PeriodIdx         
    2000-03-31  2000Q1
    2000-06-30  2000Q2
    

    【讨论】:

    • 它返回每个月的最后一个日期,而不是每个季度的最后一个日期。 (2000Q2 应该返回 2000-06-30 而不是 2000-04-30
    • @sikawit 感谢您指出这一点。使用MonthEnd(3) 很容易修复。查看更新。
    猜你喜欢
    • 2022-11-30
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    相关资源
    最近更新 更多