0
0
Pandasdata~5 mins

Swapping index levels in Pandas

Choose your learning style9 modes available
Introduction
Swapping index levels helps you change the order of row labels in a table so you can look at your data in a new way.
You want to group data by a different category first.
You need to sort or organize data differently for easier reading.
You want to prepare data for a specific analysis that requires a certain index order.
You are working with multi-level indexes and want to switch their positions.
You want to reshape your data without changing the actual values.
Syntax
Pandas
DataFrame.swaplevel(i=-2, j=-1, axis=0)
i and j are the positions or names of the index levels you want to swap.
axis=0 means you swap row index levels; use axis=1 for column index levels.
Examples
Swaps the first and second index levels of the rows.
Pandas
df.swaplevel(0, 1)
Swaps index levels named 'state' and 'city'.
Pandas
df.swaplevel('state', 'city')
Swaps the first and second index levels of the columns.
Pandas
df.swaplevel(0, 1, axis=1)
Sample Program
This example creates a table with states and cities as row labels. Then it swaps these two levels so cities come first, followed by states.
Pandas
import pandas as pd

# Create a sample DataFrame with two index levels
index = pd.MultiIndex.from_tuples(
    [('California', 'Los Angeles'), ('California', 'San Francisco'), ('Texas', 'Houston')],
    names=['state', 'city'])
data = {'population': [4000000, 884000, 2300000]}
df = pd.DataFrame(data, index=index)

# Swap the index levels
swapped_df = df.swaplevel('state', 'city')

print(swapped_df)
OutputSuccess
Important Notes
Swapping index levels does not sort the data; it only changes the order of the labels.
After swapping, you might want to sort the index for better readability using df.sort_index().
You can swap index levels by position (0, 1) or by name ('state', 'city').
Summary
Swapping index levels changes the order of row or column labels in a multi-level index.
Use swaplevel() with the positions or names of the levels you want to switch.
It helps you view and organize data differently without changing the data itself.