首页 文章

将Pandas Multi-Index变为列

提问于
浏览
98

我有一个包含2个索引级别的数据框:

value
Trial    measurement
    1              0        13
                   1         3
                   2         4
    2              0       NaN
                   1        12
    3              0        34

我想转变成这个:

Trial    measurement       value

    1              0        13
    1              1         3
    1              2         4
    2              0       NaN
    2              1        12
    3              0        34

我该怎么做才能做到最好?

我需要这个,因为我想聚合数据as instructed here,但如果它们被用作索引,我就无法选择我的列 .

2 回答

  • 11

    reset_index()是一个pandas DataFrame方法,它将索引值作为列传输到DataFrame中 . 参数的默认设置是drop = False(将索引值保留为列) .

    您只需要在DataFrame的名称后面添加 .reset_index(inplace=True)

    df.reset_index(inplace=True)
    
  • 123

    这并不适用于你的情况,但它可能对其他人(比如我5分钟前)有所帮助 . 如果一个人的多索引具有相同的名称,如下所示:

    value
    Trial        Trial
        1              0        13
                       1         3
                       2         4
        2              0       NaN
                       1        12
        3              0        34
    

    df.reset_index(inplace=True) 将失败,因为创建的列无法共享名称 .

    那么你需要用 df.index = df.index.set_names(['Trial', 'measurement']) 重命名多索引来得到:

    value
    Trial    measurement       
    
        1              0        13
        1              1         3
        1              2         4
        2              0       NaN
        2              1        12
        3              0        34
    

    然后 df.reset_index(inplace=True) 将像魅力一样工作 .

    我在按日期和月份对名为 live_date 的datetime-column(而非索引)进行分组后遇到此问题,这意味着年份和月份都命名为 live_date .

相关问题