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.
DataFrame.swaplevel(i=-2, j=-1, axis=0)
df.swaplevel(0, 1)
df.swaplevel('state', 'city')
df.swaplevel(0, 1, axis=1)
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)
swaplevel() function do in a pandas DataFrame with a multi-level index?swaplevel() function is designed to reorder the levels of a multi-level index by swapping two specified levels.df?df.swaplevel(0, 1) swaps the first and second levels correctly.df with a multi-level index:import pandas as pd
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)
print(df.swaplevel('letter', 'number'))df.swaplevel('first', 'second') but get a KeyError. What is the most likely cause?df with a multi-level index named ['city', 'year', 'month']. You want to swap the 'city' and 'month' levels and then sort the DataFrame by the new index order. Which code snippet correctly does this?swaplevel('city', 'month') swaps these levels. Then sort_index() sorts the DataFrame by the new index order.Pass the test and this pattern moves unknown