Search code examples
pythonpandasmulti-index

Specify the order of a multiindex in python pandas


I have a panda's data frame with a multiindex (that will be eventually written to a formatted Excel file), similar to the following:

first  second
one    bar      -0.292975
       baz      -0.176312
       foo      -0.458917
       qux       0.966987
two    bar       1.615486
       baz       0.875479
       foo      -3.092365
       qux      -2.348825

I would like to specify the order of the second index (note baz is always at the bottom), like so:

first  second
one    bar      -0.292975
       foo      -0.458917
       qux       0.966987
       baz      -0.176312
two    bar       1.615486
       foo      -3.092365
       qux      -2.348825
       baz       0.875479

I tried to slice the data frame like this, but it does not change the output:

myDF.loc[(slice(None),['bar','foo', 'qux', 'baz']),:]

I tried to change the index itself

myDF.index.levels[1] = pd.Index(['bar','foo', 'qux', 'baz'])

but error out with:

TypeError: 'FrozenList' does not support mutable operations.

Any suggestions are appreciated.


Solution

  • You can reindex your data (frame/Series) like so:

    new_index = ['bar','foo', 'qux', 'baz']
    v.reindex(new_index, level=1)
    
    #first  second
    #one    bar      -0.292975
    #       foo      -0.458917
    #       qux       0.966987
    #       baz      -0.176312
    #two    bar       1.615486
    #       foo      -3.092365
    #       qux      -2.348825
    #       baz       0.875479
    #Name: value, dtype: float64