Sorting a MultiIndex helps organize complex data with multiple levels, making it easier to read and analyze.
Sorting MultiIndex in Pandas
DataFrame.sort_index(level=None, ascending=True, inplace=False, sort_remaining=True)
level specifies which index levels to sort. Use names or numbers.
ascending can be a bool or list of bools to control order per level.
df.sort_index()
df.sort_index(level=0, ascending=False)
df.sort_index(level=[0,1], ascending=[True, False])
This code creates a DataFrame with a MultiIndex of letters and numbers. It shows the original order, then sorts by both index levels ascending, and finally sorts with the first level ascending and second level descending.
import pandas as pd # Create a MultiIndex DataFrame index = pd.MultiIndex.from_tuples( [('A', 2), ('A', 1), ('B', 2), ('B', 1)], names=['letter', 'number'] ) data = {'value': [10, 20, 30, 40]} df = pd.DataFrame(data, index=index) print('Original DataFrame:') print(df) # Sort by both levels ascending sorted_df = df.sort_index() print('\nSorted DataFrame by both levels ascending:') print(sorted_df) # Sort by first level ascending, second level descending sorted_df2 = df.sort_index(level=['letter', 'number'], ascending=[True, False]) print('\nSorted DataFrame by first level ascending, second level descending:') print(sorted_df2)
If you do not specify level, all index levels are sorted.
Use inplace=True to modify the DataFrame directly without creating a new one.
Sorting MultiIndex helps when you want to group and order data clearly for analysis or visualization.
Sorting MultiIndex organizes data by multiple index levels.
You can sort all levels or select specific ones.
Control ascending or descending order per level.
Practice
MultiIndex in pandas do?Solution
Step 1: Understand MultiIndex structure
A MultiIndex has multiple levels that can be sorted independently or together.Step 2: Define sorting effect
Sorting organizes rows by the values in these index levels, making data easier to analyze.Final Answer:
It arranges the data based on one or more index levels in order. -> Option DQuick Check:
Sorting MultiIndex = Arrange by index levels [OK]
- Confusing sorting with removing duplicates
- Thinking sorting changes data types
- Mixing sorting with merging DataFrames
df by its MultiIndex?Solution
Step 1: Recall sorting MultiIndex method
Usesort_index()to sort by index levels, specifying levels and order.Step 2: Check syntax correctness
df.sort_index(level=[0,1], ascending=[True, False]) correctly usessort_index(level=[0,1], ascending=[True, False]). Others use wrong methods or parameters.Final Answer:
df.sort_index(level=[0,1], ascending=[True, False]) -> Option CQuick Check:
sort_index with level and ascending = correct syntax [OK]
- Using sort_values instead of sort_index for MultiIndex
- Passing 'by' parameter to sort_index
- Using deprecated sort() method
import pandas as pd
index = pd.MultiIndex.from_tuples([('b', 2), ('a', 3), ('b', 1), ('a', 2)])
df = pd.DataFrame({'value': [10, 20, 30, 40]}, index=index)
sorted_df = df.sort_index(level=[0,1], ascending=[True, False])
print(sorted_df.index.tolist())Solution
Step 1: Understand sorting parameters
Level 0 sorted ascending (a before b), level 1 descending (higher number first).Step 2: Apply sorting to tuples
For 'a': (3,2) sorted descending gives (3), then (2). For 'b': (2,1) sorted descending gives (2), then (1).Final Answer:
[('a', 3), ('a', 2), ('b', 2), ('b', 1)] -> Option AQuick Check:
Level 0 asc, Level 1 desc = [('a',3),('a',2),('b',2),('b',1)] [OK]
- Sorting both levels ascending by default
- Confusing ascending order for level 1
- Not matching index tuples correctly
df.sort_index(level=[0,1], ascending=True, inplace=True)
What is the likely cause?
Solution
Step 1: Check parameter types for multiple levels
When sorting multiple levels, 'ascending' must be a list matching levels count.Step 2: Identify error cause
Passing a single boolean True instead of a list causes a ValueError.Final Answer:
The 'ascending' parameter must be a list when sorting multiple levels. -> Option AQuick Check:
ascending list needed for multiple levels [OK]
- Passing single bool to ascending with multiple levels
- Assuming inplace is unsupported
- Misunderstanding level parameter type
Solution
Step 1: Choose correct sorting method for MultiIndex
Usesort_index()with levels and ascending list to sort MultiIndex properly.Step 2: Reset index to flatten DataFrame
Callingreset_index()converts MultiIndex to columns, preserving sorted order.Final Answer:
df.sort_index(level=['Country', 'Year'], ascending=[True, False]).reset_index() -> Option BQuick Check:
sort_index with levels + reset_index = correct approach [OK]
- Using sort_values instead of sort_index for MultiIndex
- Wrong ascending order for levels
- Forgetting to reset index after sorting
Ready to prove it?
Pass the test and this pattern moves unknown
