How do I change order/grouping/level of pandas MultiIndex columns?

前端 未结 2 843
天涯浪人
天涯浪人 2021-01-31 16:40

I\'m trying to reorder/swaplevel/pivot/something columns in a pandas dataframe. The columns are a MultiIndex, but I can\'t find the sauce to do what I want.

The fastest

相关标签:
2条回答
  • 2021-01-31 16:53

    Your columns are a MultiIndex. You need to reassign the DataFrame's columns with a new MultiIndex created from swapping levels of the existing one:

    df.columns = df.columns.swaplevel(0, 1)
    df.sortlevel(0, axis=1, inplace=True)
    >>> df
    
    month   '1Jan'                 'Feb'                 'Mar'              
            weight  extent  rank  weight  extent  rank  weight  extent  rank
    year                                                                    
    2000      45.1  13.442    13    46.1   14.94    17    25.1   15.02    14
    2001      85.0  13.380    12    16.0   14.81    15    49.0   15.14    17
    2002      90.0  13.590    15    33.0   15.13    22    82.0   14.88    10
    2003      47.0  13.640    17    34.0   14.83    16    78.0   15.27    22
    

    You can then export to csv:

    df.to_csv(filename)
    

    EDIT

    Per the comment from @Silas below, sortlevel has been deprecated. Instead, use:

    df.sort_index(axis=1, level=0, inplace=True)
    
    0 讨论(0)
  • 2021-01-31 17:08

    Since levels indices are no more mandatory you can have even more simple way to achieve the level swapping of multi-index dataframe:

    df = df.swaplevel(axis='columns')
    
    0 讨论(0)
提交回复
热议问题