0
0
Pandasdata~20 mins

Swapping index levels in Pandas - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Master of Swapping Index Levels
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
What is the output after swapping index levels?
Given a pandas DataFrame with a MultiIndex, what will be the index order after swapping the two levels using df.swaplevel()?
Pandas
import pandas as pd

index = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1)])
df = pd.DataFrame({'value': [10, 20, 30]}, index=index)
swapped = df.swaplevel()
A[('A', 1), ('A', 2), ('B', 1)]
B[('B', 1), ('A', 2), ('A', 1)]
C[(1, 'B'), (2, 'A'), (1, 'A')]
D[(1, 'A'), (2, 'A'), (1, 'B')]
Attempts:
2 left
💡 Hint
Think about what swapping index levels means: the first level becomes second and the second becomes first.
📝 Syntax
intermediate
1:30remaining
Which code correctly swaps index levels in pandas?
Identify the correct syntax to swap the two levels of a MultiIndex in a pandas DataFrame named df.
Adf.swaplevel(0, 1)
Bdf.swaplevel(level1=0, level2=1)
Cdf.swaplevel(levels=(0,1))
Ddf.swap_level(0, 1)
Attempts:
2 left
💡 Hint
Check the exact method name and parameter names in pandas documentation.
optimization
advanced
2:00remaining
How to efficiently swap index levels and sort the DataFrame?
You want to swap the two levels of a MultiIndex in a DataFrame df and then sort the DataFrame by the new index order. Which option achieves this efficiently?
Adf.swaplevel(levels=(1,0)).sort_values()
Bdf.sort_index().swaplevel()
Cdf.swaplevel().sort_index()
Ddf.sort_values().swaplevel()
Attempts:
2 left
💡 Hint
Remember that sorting by index should happen after swapping the index levels.
🔧 Debug
advanced
1:30remaining
Why does this swaplevel call raise an error?
Consider this code snippet:
df.swaplevel(level=0, level=1)
Why does it raise a SyntaxError or TypeError?
Pandas
df.swaplevel(level=0, level=1)
ABecause swaplevel requires positional arguments, not keywords.
BBecause the method does not accept keyword arguments named 'level' twice.
CBecause the index levels do not exist in the DataFrame.
DBecause swaplevel only works on single-level indexes.
Attempts:
2 left
💡 Hint
Check the function call syntax and parameter names carefully.
🧠 Conceptual
expert
2:30remaining
What happens to the index names after swapping levels?
If a MultiIndex has names ['first', 'second'], what will be the names after calling df.swaplevel() without arguments?
Pandas
import pandas as pd
index = pd.MultiIndex.from_tuples([('x', 1), ('y', 2)], names=['first', 'second'])
df = pd.DataFrame({'val': [5, 10]}, index=index)
swapped = df.swaplevel()
A['second', 'first']
B['first', 'second']
C['first_second', 'second_first']
D[None, None]
Attempts:
2 left
💡 Hint
Swapping index levels also swaps their names in the same order.