【问题标题】:Converting a Pandas datetime index on a DataFrame object to *MultiIndex* with the levels "month" and "year"将 DataFrame 对象上的 Pandas 日期时间索引转换为具有“月”和“年”级别的 *MultiIndex*
【发布时间】:2017-07-27 04:20:54
【问题描述】:

假设我有一个包含 monthly datetime 索引的数据表(以下代码给出了两年,从 1 月到 12 月):

import pandas as pd
import numpy as np
from datetime import datetime
N = 12*2
c = [datetime(1970 + i//12, (i%12)+1, 1) for i in range(N)]
d = pd.DataFrame(np.random.rand(N), index=c)
print(d)

DateTimeIndex 转换为具有单独级别 monthyearMultiIndex 的最佳方法是什么?也许有一种方法可以通过groupby 做到这一点,但我不确定。

【问题讨论】:

    标签: python python-3.x pandas datetime dataframe


    【解决方案1】:

    您可以从yearmonth 构造一个MultiIndex 对象并将其分配给数据框的索引:

    import pandas as pd
    d.index = pd.MultiIndex.from_arrays([d.index.year, d.index.month])
    
    d.index
    # MultiIndex(levels=[[1970, 1971], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
    #            labels=[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]])
    
    d.head()
    
    #                  0
    #1970   1   0.657130
    #       2   0.047241
    #       3   0.984799
    #       4   0.868508
    #       5   0.678536
    

    【讨论】:

      【解决方案2】:
      d.index = pd.MultiIndex.from_tuples(d.reset_index()['index'].\
                                          apply(lambda x:(x.year,x.month)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-12
        • 1970-01-01
        • 2015-07-19
        • 1970-01-01
        • 2018-03-03
        • 1970-01-01
        • 2019-07-30
        相关资源
        最近更新 更多