Challenge - 5 Problems
Master of Swapping Index Levels
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2: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()
Attempts:
2 left
💡 Hint
Think about what swapping index levels means: the first level becomes second and the second becomes first.
✗ Incorrect
The
swaplevel() method switches the positions of the two index levels. So the original index [('A',1), ('A',2), ('B',1)] becomes [(1,'A'), (2,'A'), (1,'B')].📝 Syntax
intermediate1: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.Attempts:
2 left
💡 Hint
Check the exact method name and parameter names in pandas documentation.
✗ Incorrect
The correct method is
swaplevel with positional arguments for the two levels to swap. The other options use incorrect method names or parameter names.❓ optimization
advanced2: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?Attempts:
2 left
💡 Hint
Remember that sorting by index should happen after swapping the index levels.
✗ Incorrect
Swapping the levels first and then sorting by index ensures the DataFrame is ordered by the new index. Sorting before swapping does not sort by the new index order.
🔧 Debug
advanced1: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)
Attempts:
2 left
💡 Hint
Check the function call syntax and parameter names carefully.
✗ Incorrect
The code uses the same keyword argument 'level' twice, which is invalid syntax in Python. The correct way is to use positional arguments or keywords
i=0 and j=1.🧠 Conceptual
expert2: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()
Attempts:
2 left
💡 Hint
Swapping index levels also swaps their names in the same order.
✗ Incorrect
The
swaplevel() method swaps both the index levels and their names. So the names change from ['first', 'second'] to ['second', 'first'].