Pandas MultiIndex Swap Level Quick Fix
You will learn how to swap levels of a pandas MultiIndex using .swaplevel() to restructure hierarchical axes for easier slicing and grouping.
The Problem
When a MultiIndex has levels in an inconvenient order -- for example, (city, year) but you need (year, city) for seasonal analysis -- rebuilding the index from scratch is wasteful. The .swaplevel() method provides a one-call fix.
The Wrong Way
import pandas as pd
idx = pd.MultiIndex.from_tuples([("NYC", 2023), ("NYC", 2024),
("LA", 2023), ("LA", 2024)],
names=["city", "year"])
df = pd.DataFrame({"sales": [100, 110, 90, 95]}, index=idx)
# Manually rebuilding
new_tuples = [(year, city) for city, year in df.index]
new_idx = pd.MultiIndex.from_tuples(new_tuples, names=["year", "city"])
print(new_idx)
Output:
MultiIndex([(2023, 'NYC'), (2024, 'NYC'), (2023, 'LA'), (2024, 'LA')],
names=['year', 'city'])
This works but is verbose and error-prone.
The Right Way
df2 = df.swaplevel("city", "year")
print(df2)
Output:
sales
year city
2023 NYC 100
2024 NYC 110
2023 LA 90
2024 LA 95
One line swaps the levels, preserving all data and names.
Step-by-Step Fix
1. Identify the levels to swap
print(df.index.names) # ['city', 'year']
2. Call .swaplevel()
df2 = df.swaplevel("city", "year")
# or by position: df.swaplevel(0, 1)
3. Sort the new index for performance
df2 = df2.sort_index()
Prevention Tips
- Use
.swaplevel()instead of rebuilding for level reordering - Pass level names as strings for readability instead of integer positions
- Chain with
.sort_index()after swapping to enable fast label-based slicing - Remember that
.swaplevel()operates on the specified axis (default 0 for rows)
Common Mistakes
- Forgetting to sort after swap -- unsorted MultiIndex causes
PerformanceWarningon slicing - Confusing
.swaplevel()with.reorder_levels()-- swap exchanges two levels; reorder can rearrange all levels - Using integer positions without verifying current order -- leads to swapping the wrong levels
These mistakes appear frequently in real-world pandas code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tools integrate seamlessly with pandas for enhanced productivity and security.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro