What will be the first row's index after swapping?
medium
A. (1, 'A')
B. ('A', 1)
C. ('number', 'letter')
D. (10, 20)
Solution
Step 1: Understand original index order
The original index is [('A',1), ('A',2), ('B',1), ('B',2)] with levels 'letter' then 'number'.
Step 2: Swap levels 'letter' and 'number'
After swapping, the order becomes 'number' then 'letter'. So the first index becomes (1, 'A').
Final Answer:
(1, 'A') -> Option A
Quick Check:
Swapped index order changes ('A',1) to (1,'A') [OK]
Hint: Swapping levels flips their order in the index tuple [OK]
Common Mistakes:
Assuming index values stay in same order
Confusing index values with column values
Mixing up level names and positions
4. You try to swap index levels in a DataFrame using df.swaplevel('first', 'second') but get a KeyError. What is the most likely cause?
medium
A. The level names 'first' and 'second' do not exist in the index.
B. swaplevel() requires integer positions, not names.
C. The DataFrame has no multi-level index.
D. You must reset the index before swapping levels.
Solution
Step 1: Check index level names
swaplevel() accepts level names, but if the names given do not exist, a KeyError occurs.
Step 2: Confirm cause of KeyError
The error means 'first' and 'second' are not valid level names in the DataFrame's index.
Final Answer:
The level names 'first' and 'second' do not exist in the index. -> Option A
Quick Check:
KeyError means invalid level names [OK]
Hint: Verify level names exist before swapping [OK]
Common Mistakes:
Assuming swaplevel() only accepts integers
Not checking if DataFrame has multi-level index
Resetting index unnecessarily
5. You have a DataFrame 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?
hard
A. df_swapped = df.swaplevel('year', 'month').sort_index()
B. df_swapped = df.swaplevel(0, 1).sort_values()
C. df_swapped = df.swaplevel('city', 'month').sort_index()
D. df_swapped = df.swaplevel('city', 'month').reset_index()
Solution
Step 1: Identify correct levels to swap
The levels to swap are 'city' and 'month', which are the first and third levels.
Step 2: Use swaplevel() with level names and sort_index()
Calling swaplevel('city', 'month') swaps these levels. Then sort_index() sorts the DataFrame by the new index order.
Final Answer:
df_swapped = df.swaplevel('city', 'month').sort_index() -> Option C
Quick Check:
Swap specified levels then sort index [OK]
Hint: Swap by names, then sort_index() to reorder rows [OK]
Common Mistakes:
Swapping wrong levels by position
Using sort_values() instead of sort_index()
Resetting index instead of sorting
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.