【问题标题】:Pandas: Converting index of YYYYQQ values to datetime objectPandas:将 YYYYQQ 值的索引转换为日期时间对象
【发布时间】:2018-03-03 04:41:56
【问题描述】:

我有以下数据框:

df = pd.DataFrame({'A':[1,2,3],'B':[4,3,2]},index = ['201701','201702','201703'])

其中字符串值的索引是格式为 YYYYQQ(季度数据)的日期。

当我尝试将其转换为日期时间对象时,出现错误:

pd.to_datetime(df.index)
....
ValueError: month must be in 1...12

我觉得这一定是由于 to_datetime 推断 df.index 的格式,但我找不到解决方法。有什么帮助吗?

更新:@Zero 的回答也有效,但这最终也是一个解决方案:

pd.to_datetime([x[:-2] + str(int(x[-2:])*3) for x in df.index], format = '%Y%m')

【问题讨论】:

    标签: python pandas datetime dataframe


    【解决方案1】:

    使用

    In [2325]: [pd.to_datetime(x[:4]) + pd.offsets.QuarterBegin(int(x[5:])) for x in df.index]
    Out[2325]:
    [Timestamp('2017-03-01 00:00:00'),
     Timestamp('2017-06-01 00:00:00'),
     Timestamp('2017-09-01 00:00:00')]
    

    【讨论】:

    • 这适用于月度数据,但这是季度数据。最后两位数字对应季度
    • Q1 不应该从 1 月开始,而不是 3 月开始吗?
    • 财务第一季度是三月,至少在这个地区。
    • 那么这很重要,但要注意歧义:来自pandas docs,“季度季度日期:Jan-Mar = 1,Apr-Jun = 2 等”
    【解决方案2】:

    我会使用 Pandas Period:

    In [92]: x = pd.PeriodIndex(df.index.astype(str).str.replace(r'0(\d)$', r'q\1'), freq='Q')
    
    In [93]: x
    Out[93]: PeriodIndex(['2017Q1', '2017Q2', '2017Q3'], dtype='period[Q-DEC]', freq='Q-DEC')
    
    In [94]: x.to_timestamp()
    Out[94]: DatetimeIndex(['2017-01-01', '2017-04-01', '2017-07-01'], dtype='datetime64[ns]', freq='QS-OCT')
    

    【讨论】:

      猜你喜欢
      • 2014-07-28
      • 2018-10-30
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-07-11
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多