5. You have a DataFrame df with a MultiIndex on rows (levels: 'City', 'Year') and columns as years (e.g., 2020, 2021). You want to reshape it so that the 'Year' level from rows becomes columns, and the columns years become a new row level. Which sequence of operations correctly achieves this?
hard
A. First unstack the 'Year' level from rows, then stack the columns.
B. First stack the columns, then unstack the 'City' level from rows.
C. Use only stack on the columns without unstacking rows.
D. Use only unstack on the 'City' level.
Solution
Step 1: Unstack the 'Year' level from rows
Unstacking the 'Year' level moves it from the row index to columns, widening the DataFrame.
Step 2: Stack the columns
Stacking the columns moves the columns years into a new row index level, making the data longer again but reshaped as desired.
Final Answer:
First unstack the 'Year' level from rows, then stack the columns. -> Option A
Quick Check:
Unstack rows then stack columns reshapes MultiIndex correctly [OK]
Hint: Unstack row level first, then stack columns to reshape MultiIndex [OK]
Common Mistakes:
Stacking before unstacking causes wrong shape
Unstacking wrong index level
Ignoring the need to reshape both rows and columns
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.