Swap MultiIndex Levels in Pandas DataFrame
Pandas: Advanced Indexing and Slicing Exercise-5 with Solution
Swap MultiIndex Levels:
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.
Python-Pandas Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Slice DataFrame with MultiIndex in Pandas.
Next: Reset index of MultiIndex DataFrame in Pandas.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/pandas/swap-multiindex-levels-in-pandas-dataframe.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics