Understand the idea
pivot spreads a measurement-label column across new columns. It rearranges existing values without calculating a summary.
A small example
Ada · age · 4 and Ada · weight · 8 become one Ada row with age=4 and weight=8.
Follow the code
Apply the idea to the supplied table. Read from top to bottom; the final line displays the result.
long.pivot(index="candy", columns="measure", values="value")What each part does
long.pivot(...)- Reshape the supplied long table into wider rows.
index="candy"- Use each candy name to identify an output row.
columns="measure"- Turn each measure label into an output column.
values="value"- Put each corresponding value into its new cell.
Your inputs
The editable setup on the right creates df and the additional inputs shown below. Run executes the setup and your work from top to bottom.
| candy | flavour | price | rating | shelf |
|---|---|---|---|---|
| Gummy Bear | fruity | 1.2 | 4.1 | A |
| Choco Pop | chocolate | 2.1 | 4.6 | B |
| Mint Bite | mint | 1.5 | 3.8 | A |
| Berry Loop | fruity | 2.8 | 4.4 | B |
| Cocoa Cube | chocolate | 3.4 | 4.9 | A |
| Lemon Drop | fruity | 1.8 | 4 | B |
| candy | measure | value |
|---|---|---|
| Gummy Bear | price | 1.2 |
| Choco Pop | price | 2.1 |
| Mint Bite | price | 1.5 |
| Berry Loop | price | 2.8 |
| Cocoa Cube | price | 3.4 |
| Lemon Drop | price | 1.8 |
| Gummy Bear | rating | 4.1 |
| Choco Pop | rating | 4.6 |
| Mint Bite | rating | 3.8 |
| Berry Loop | rating | 4.4 |
| Cocoa Cube | rating | 4.9 |
| Lemon Drop | rating | 4 |
Your task · Follow
- The supplied long table contains candy, measure and value.
- Pivot it back with candy on rows, measure on columns and value in cells.
- Use: pivot().
Hint
pivot needs one value per identifier/measure pair and does not aggregate repeats.
Reveal solution
One way to do it. Keep any supplied setup in the editor and use this in the Your work section.
long.pivot(index="candy", columns="measure", values="value")Optional stretch
Duplicate one row in long with pd.concat([long, long.head(1)]). Why does pivot reject it?