Prepend a level to a pandas MultiIndex

后端 未结 5 716
一向
一向 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 02:50

    A nice way to do this in one line using pandas.concat():

    import pandas as pd
    
    pd.concat([df], keys=['Foo'], names=['Firstlevel'])
    

    An even shorter way:

    pd.concat({'Foo': df}, names=['Firstlevel'])
    

    This can be generalized to many data frames, see the docs.

提交回复
热议问题