0
0
PandasHow-ToBeginner · 3 min read

How to Use swaplevel in pandas for MultiIndex DataFrames

In pandas, you can use the swaplevel() method to interchange two levels of a MultiIndex in a DataFrame or Series. This method takes optional parameters i and j to specify which levels to swap, and it returns a new object with the levels swapped.
📐

Syntax

The swaplevel() method syntax is:

  • swaplevel(i=-2, j=-1, axis=0)

Where:

  • i and j are the two level numbers or names to swap. Defaults are the last two levels.
  • axis specifies whether to swap index levels (axis=0) or columns levels (axis=1).
python
DataFrame.swaplevel(i=-2, j=-1, axis=0)
💻

Example

This example shows how to swap the two levels of a MultiIndex in a DataFrame's index.

python
import pandas as pd

# Create a MultiIndex DataFrame
index = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2)], names=['letter', 'number'])
df = pd.DataFrame({'value': [10, 20, 30, 40]}, index=index)

# Swap the levels of the index
swapped_df = df.swaplevel('letter', 'number')

print("Original DataFrame:\n", df)
print("\nDataFrame after swaplevel:\n", swapped_df)
Output
Original DataFrame: value letter number A 1 10 2 20 B 1 30 2 40 DataFrame after swaplevel: value number letter 1 A 10 2 A 20 1 B 30 2 B 40
⚠️

Common Pitfalls

Common mistakes when using swaplevel() include:

  • Not specifying the correct level names or numbers, which can cause errors or unexpected results.
  • Forgetting that swaplevel() does not sort the index automatically, so the order might look confusing after swapping.
  • Using swaplevel() on a DataFrame without a MultiIndex will raise an error.

Always check your index levels with df.index.names before swapping.

python
import pandas as pd

# DataFrame without MultiIndex
simple_df = pd.DataFrame({'value': [1, 2, 3]})

try:
    simple_df.swaplevel()
except Exception as e:
    print(f"Error: {e}")

# Correct usage with MultiIndex
index = pd.MultiIndex.from_tuples([('X', 'a'), ('Y', 'b')], names=['first', 'second'])
df = pd.DataFrame({'val': [100, 200]}, index=index)

# Swap levels by position
swapped = df.swaplevel(0, 1)
print(swapped)
Output
Error: Can only swap levels on a MultiIndex val second first a X 100 b Y 200
📊

Quick Reference

Remember these tips when using swaplevel():

  • Use i and j to specify which levels to swap by name or position.
  • Default swaps the last two levels if no arguments are given.
  • Works on index (axis=0) or columns (axis=1).
  • Does not sort the index after swapping; use sort_index() if needed.

Key Takeaways

Use pandas swaplevel() to interchange two levels of a MultiIndex in DataFrame or Series.
Specify levels by name or position with i and j parameters; defaults swap last two levels.
swaplevel() does not sort the index automatically after swapping.
swaplevel() only works on MultiIndex; using it on a simple index raises an error.
Use sort_index() after swaplevel() if you want the index sorted.