0
0
Pandasdata~10 mins

Swapping index levels in Pandas - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Swapping index levels
Start with MultiIndex DataFrame
Choose levels to swap
Call swaplevel(level1, level2)
New DataFrame with swapped index levels
Use swapped DataFrame for further operations
Swapping index levels means exchanging positions of two levels in a MultiIndex DataFrame to change how data is grouped or accessed.
Execution Sample
Pandas
import pandas as pd
idx = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1)])
df = pd.DataFrame({'val': [10, 20, 30]}, index=idx)
df_swapped = df.swaplevel(0, 1)
This code creates a DataFrame with a two-level index and swaps the two index levels.
Execution Table
StepActionIndex BeforeIndex AfterResulting DataFrame Index
1Create MultiIndex from tuples [('A',1), ('A',2), ('B',1)][('A',1), ('A',2), ('B',1)][('A',1), ('A',2), ('B',1)]MultiIndex with level0: ['A','A','B'], level1: [1,2,1]
2Create DataFrame with MultiIndex[('A',1), ('A',2), ('B',1)][('A',1), ('A',2), ('B',1)]DataFrame with index levels 0:'A','A','B' and 1:1,2,1
3Call swaplevel(0,1) to swap index levels[('A',1), ('A',2), ('B',1)][(1,'A'), (2,'A'), (1,'B')]DataFrame index levels swapped: level0: [1,2,1], level1: ['A','A','B']
4Use swapped DataFrame for further operations[(1,'A'), (2,'A'), (1,'B')][(1,'A'), (2,'A'), (1,'B')]DataFrame now grouped/indexed by swapped levels
💡 All steps complete; index levels successfully swapped
Variable Tracker
VariableStartAfter Step 1After Step 3Final
idxNone[('A',1), ('A',2), ('B',1)][('A',1), ('A',2), ('B',1)][('A',1), ('A',2), ('B',1)]
df.indexNoneNone[('A',1), ('A',2), ('B',1)][('A',1), ('A',2), ('B',1)]
df_swapped.indexNoneNone[(1,'A'), (2,'A'), (1,'B')][(1,'A'), (2,'A'), (1,'B')]
Key Moments - 2 Insights
Why does the order of index levels matter after swapping?
The order of index levels affects how data is grouped and accessed. After swapping (see execution_table step 3), the first level becomes the previous second level, changing grouping and sorting behavior.
Does swaplevel change the data or just the index structure?
swaplevel only changes the order of index levels, not the data itself. The rows remain the same but are accessed differently (see execution_table step 3 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the new first index level after swaplevel(0,1)?
AA combination of both levels
BThe original first level values ['A', 'A', 'B']
CThe original second level values [1, 2, 1]
DAn empty index
💡 Hint
Check the 'Index After' column at step 3 in execution_table
At which step does the DataFrame index actually change to swapped levels?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the 'Resulting DataFrame Index' column in execution_table
If you swap levels back again after step 3, what will the index look like?
ASwapped index [(1,'A'), (2,'A'), (1,'B')]
BSame as original index [('A',1), ('A',2), ('B',1)]
CIndex with only one level
DIndex with levels reversed but values changed
💡 Hint
Swapping twice returns index to original order (see variable_tracker for df_swapped.index)
Concept Snapshot
swaplevel(level1, level2) swaps two index levels in a MultiIndex DataFrame.
It changes the order of index levels but not the data.
Useful for changing grouping or sorting order.
Returns a new DataFrame with swapped index levels.
Example: df.swaplevel(0,1) swaps first and second index levels.
Full Transcript
This visual execution shows how to swap index levels in a pandas MultiIndex DataFrame. We start with a MultiIndex created from tuples [('A',1), ('A',2), ('B',1)]. The DataFrame uses this MultiIndex as its index. When we call swaplevel(0,1), the first and second index levels exchange places. The index changes from level0: ['A','A','B'] and level1: [1,2,1] to level0: [1,2,1] and level1: ['A','A','B']. This affects how the DataFrame is grouped and accessed but does not change the data itself. Swapping again would restore the original index order. This technique helps reorganize data views without altering the underlying data.