How to sort MultiIndex using values from a given column


I have a DataFrame with 2-level index and column with the numerical values. I want to sort it by level-0 and level-1 index in such a way that the the order of 0-level index is determined by the sum of values from Value column (descending), and the order of 1-level index is also determined by the values in Value column. This is my code:

import pandas as pd

df = pd.DataFrame()
df["Index1"] = ["A", "A", "B", "B", "C", "C"]
df["Index2"] = ["X", "Y", "X", "Y", "X", "Y"]
df["Value"] = [1, 4, 7, 3, 2, 7]
df = df.set_index(["Index1", "Index2"])

And this is the desired output (B is at the top because the sum is 10 and then we have X first because 7 >3):
enter image description here

Asked By: Jason



You can do this with pandas.DataFrame.sort_values :

out= (
         .assign(temp_col = df.groupby(level=0).transform("sum"))
         .sort_values(by=["temp_col", "Value"], ascending=[False, False])

# Output :


Index1 Index2       
B      X           7
       Y           3
C      Y           7
       X           2
A      Y           4
       X           1
Answered By: abokey
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.