chevron_left
Multi-index Operations Cookbook
0
0
0
new
Sorting a multi-index DataFrame in Pandas
Programming
chevron_rightPython
chevron_rightPandas
chevron_rightCookbooks
chevron_rightDataFrame Cookbooks
chevron_rightMulti-index Operations Cookbook
schedule Mar 9, 2022
Last updated Python●Pandas
Tags tocTable of Contents
expand_more To sort a multi-index DataFrame, use the DataFrame's sort_index(~)
method.
Examples
Consider the following DataFrame:
index = [("B", "bob"), ("B", "cathy"),("A", "david"),("A","alice")]multi_index = pd.MultiIndex.from_tuples(index)df
age heightB bob 2 6 cathy 3 7A david 4 8 alice 5 9
Sorting all levels
To sort all levels:
age heightA alice 5 9 david 4 8B bob 2 6 cathy 3 7
Notice how levels are sorted starting from the first level.
Specifying levels to sort
To sort just the outermost level:
age heightA alice 5 9 david 4 8B bob 2 6 cathy 3 7
Although not mentioned in the official documentation, values at higher levels get sorted as well, as can be seen from alice
now appearing before david
.
To sort level 1
instead:
age heightA alice 5 9B bob 2 6 cathy 3 7A david 4 8
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
Ask a question or leave a feedback...