Swap MultiIndex Levels in Pandas DataFrame
5. Swap Levels of a MultiIndex DataFrame
Write a Pandas program to swap the levels of a MultiIndex DataFrame.
Sample Solution :
Python Code :
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
    'X': [1, 6, 8, 3, 7],
    'Y': [5, 2, 9, 4, 1],
    'Z': ['one', 'one', 'two', 'two', 'one']
})
# Set MultiIndex
df = df.set_index(['Z', 'X'])
# Swap the levels of the MultiIndex
df = df.swaplevel()
print(df)
Output:
          Y
X Z     
1 one  5
6 one  2
8 two  9
3 two  4
7 one  1
Explanation:
- Import pandas library.
- Create a DataFrame.
- Set a MultiIndex using columns 'Z' and 'X'.
- Swap the levels of the MultiIndex.
- Print the DataFrame.
For more Practice: Solve these Related Problems:
- Write a Pandas program to swap the levels of a MultiIndex DataFrame and display the new index order.
- Write a Pandas program to interchange the two index levels in a MultiIndex and verify by sorting the DataFrame.
- Write a Pandas program to swap MultiIndex levels and then select data using the new index order.
- Write a Pandas program to create a pivot table with a MultiIndex and then swap its index levels using swaplevel().
Go to:
PREV : Slice DataFrame Based on MultiIndex Levels.
NEXT :
 Reset Index of a MultiIndex DataFrame.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
