Search code examples
pythonpandasdataframesortingmulti-level

How to sort by column value in a multi column index dataframe?


I have a multi-index dataframe and need to sort the columns by the second level so that the column with 0.1 is first, does anyone know how to do this?

            WBAI           ANF           ACEL             
            0.3           0.2           0.1
2018-05-14  17.490000     23.185350     9.861    

Solution

  • You can use sort_index setting axis=1 (i.e., using columns) and level=1 (counting starts from 0 so 1 is the second level) as follows:

    df = df.sort_index(axis=1, level=1)
    

    Result:

                 ACEL        ANF     WBAI
                  0.1        0.2      0.3
    2018-05-14  9.861   23.18535    17.49