Prepend a level to a pandas MultiIndex

后端 未结 5 710
一向
一向 2020-11-28 02:25

I have a DataFrame with a MultiIndex created after some grouping:

import numpy as np
import pandas as p
from numpy.random import randn

df = p.DataFrame({
           


        
5条回答
  •  借酒劲吻你
    2020-11-28 03:05

    You can first add it as a normal column and then append it to the current index, so:

    df['Firstlevel'] = 'Foo'
    df.set_index('Firstlevel', append=True, inplace=True)
    

    And change the order if needed with:

    df.reorder_levels(['Firstlevel', 'A', 'B'])
    

    Which results in:

                          Vals
    Firstlevel A  B           
    Foo        a1 b1  0.871563
                  b2  0.494001
               a2 b3 -0.167811
               a3 b4 -1.353409
    

提交回复
热议问题