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:
JavaScript
x
9
1
import pandas as pd
2
3
df = pd.DataFrame()
4
df["Index1"] = ["A", "A", "B", "B", "C", "C"]
5
df["Index2"] = ["X", "Y", "X", "Y", "X", "Y"]
6
df["Value"] = [1, 4, 7, 3, 2, 7]
7
df = df.set_index(["Index1", "Index2"])
8
df
9
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):
Advertisement
Answer
You can do this with pandas.DataFrame.sort_values
:
JavaScript
1
7
1
out= (
2
df
3
.assign(temp_col = df.groupby(level=0).transform("sum"))
4
.sort_values(by=["temp_col", "Value"], ascending=[False, False])
5
.drop(columns="temp_col")
6
)
7
# Output :
JavaScript
1
11
11
1
print(out)
2
3
Value
4
Index1 Index2
5
B X 7
6
Y 3
7
C Y 7
8
X 2
9
A Y 4
10
X 1
11