【问题标题】:Pandas convert a DataFrame [monthly data] with index 0 1 2 ... to a specific date Year-month rangePandas 将索引为 0 1 2 ... 的 DataFrame [monthly data] 转换为特定日期年月范围
【发布时间】:2019-07-22 09:42:12
【问题描述】:

我有一个大小为 365,1 的 panda DataFrame 数据按月计算。 当前索引为 0 1 2 ... 我想将当前索引转换为年月格式,其中第一个月是 1987 年 1 月。 所以索引 0 应该由 1978 January 替换,索引 1 由 1987 February 替换,等等。

我累了

pd.to_datetime(df, unit='m', origin=pd.Timestamp('1987-01-01'))

但我一定做错了什么,因为它给了我错误

 unit='m' not valid with non-numerical val='[8940982.93]'

【问题讨论】:

    标签: python pandas date


    【解决方案1】:

    您可以通过DateOffset查看

    s=df.index.map(lambda x : pd.DateOffset(months=x) + pd.to_datetime('1978-01-01'))
    s.strftime('%Y-%B')
    Index(['1978-January', '1978-February', '1978-March', '1978-April', '1978-May',
           '1978-June', '1978-July', '1978-August', '1978-September',
           '1978-October'],
          dtype='object')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-23
      • 2017-07-27
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      相关资源
      最近更新 更多