HomeCourseModule 10 › Reshape — melt and pivot

Reshape — melt and pivot

Module 10 · Data Cleaning and Transformation8 min readIntermediate

What you'll learn

  • Use melt() to turn wide data long
  • Use pivot() to turn long data wide
  • Recognise when each shape is the right one

Wide vs long

Wide has one row per "thing" and many columns:

region   Q1    Q2    Q3    Q4
North   1200  1500  1300  1700
South    900  1100  1050   950

Long has one row per observation:

region   quarter  amount
North    Q1       1200
North    Q2       1500
North    Q3       1300
North    Q4       1700
South    Q1        900
...

Long is friendlier for grouping/plotting; wide is friendlier for humans.

Wide → long with melt

long = df.melt(id_vars="region",
               value_vars=["Q1","Q2","Q3","Q4"],
               var_name="quarter",
               value_name="amount")

Long → wide with pivot

wide = long.pivot(index="region", columns="quarter", values="amount")

When to reshape

Key takeaways

  • melt() turns wide to long.
  • pivot() turns long to wide.
  • Long shape is what most analysis tools prefer.

Quarterly to long

Take a wide DataFrame of quarterly figures by region. Melt it into long form. Then pivot it back.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.