pandas Reshaping: Pivot, Melt and Wide-to-Long Exercises With Answers
Practise reshaping with small examples.
The Open buttons send the prompt text as currently shown below to that site only when you click. Fill in the placeholders first.
[VERIFY] is an editorial flag, not a blank to fill. Wherever the prompt shows [VERIFY], check that item against a reliable source before you use it.
Create reshaping practice for pandas. My typical data layouts (a wide table with one column per month, or a long table of events): [DATA_LAYOUTS]. Tasks I struggle with: [TASKS]. Provide five self-contained exercises with small invented DataFrames described in text and checkable answers: wide to long with melt, long to wide with pivot or pivot_table, handling duplicate index entries, multi-level columns flattened, and stacking and unstacking. For each give the starting table, the target table, hints, solution code and why it works. Exercise one in full: wide table with Region, Jan, Feb, Mar (North 100, 120, 90; South 80, 95, 110; West 60, 70, 65); target a long table with Region, Month, Sales in nine rows; hint: use melt with id_vars and var_name; check nine rows and total 790 (column order may differ). Exercise two: long to wide with pivot_table and a sum. Exercise three: a duplicate (two rows for North and Jan) shows why pivot fails and pivot_table with aggregation fixes it. Add an answer key, a cheat sheet of when to use each function and the shape change (3 customers by 12 months becomes 36 rows; the row-count rule to check each exercise), and five debugging cases (pivot with duplicates, melt duplicating id columns, a multi-index that will not save to a simple table, a stack dropping missing values, a merge after reshaping that doubles rows). Final mini-project: a wide survey of 12 question columns for 100 respondents, reshape, average per question, and verify 1,200 rows after melting. Mark untested code [VERIFY].
Fill in before use
Optional: type your details and the prompt above updates. Nothing is saved or sent.
Replace each bracketed placeholder with your own details, then paste into Any AI or another assistant.