【问题标题】:Convert pandas multiindex to datetime format将 pandas 多索引转换为日期时间格式
【发布时间】:2017-07-11 01:59:17
【问题描述】:

我在 pandas 中有一个多索引,看起来像以下代码生成的那样:

arrays = [[2001, 2001, 2003, 2004], ['January', 'March', 'June', 'December']]
tuples= list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['year', 'month'])

我想将此索引转换为单个日期时间索引。我尝试使用

pd.to_datetime(index, format="%Y %B")

但它给了我一个错误。

您能否就如何以最有效的方式完成此任务提供一些帮助?

谢谢

【问题讨论】:

    标签: python pandas datetime multi-index


    【解决方案1】:

    你可以先使用map

    idx = index.map(lambda x: ''.join((str(x[0]), x[1])))
    print (idx)
    ['2001January' '2001March' '2003June' '2004December']
    
    print (pd.to_datetime(idx, format="%Y%B"))
    DatetimeIndex(['2001-01-01', '2001-03-01', '2003-06-01', '2004-12-01'],
                   dtype='datetime64[ns]', freq=None)
    

    另一种解决方案:

    idx = index.map(lambda x: '{}{}'.format(x[0], x[1]))
    print (idx)
    ['2001January' '2001March' '2003June' '2004December']
    

    或者list comprehension解决方案:

    idx = ['{}{}'.format(x[0], x[1]) for x in index]
    print (idx)
    ['2001January', '2001March', '2003June', '2004December']
    

    【讨论】:

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