Skip to main content
Albero Academy

Reshaping: Pivot, Melt & Stack

Move between wide and long layouts — melt, pivot, stack and unstack — and understand the tidy-data shape your tools expect.

Chapter 6Pandas15 min readBeginner friendly
  • #Pandas
  • #Reshaping
  • #Tidy Data

The same data can be laid out wide (a column per month) or long (one row per observation). Plotting and grouping want long "tidy" data; reports want wide. Reshaping fluently between them is a core skill — and the source of much pandas confusion until it clicks.

Wide vs long (tidy) data

Tidy (long) data has one variable per column and one observation per row. It's the shape groupby, pivot_table and plotting libraries expect:

two layouts of the same data
# WIDE: a column per month
# name jan feb mar
# Aanya 10 12 15
# LONG (tidy): one row per (name, month)
# name month sales
# Aanya jan 10
# Aanya feb 12

melt — wide to long

melt collapses many value columns into two: a variable name and its value:

unpivot
long = wide.melt(
id_vars=["name"], # columns to keep as-is
value_vars=["jan", "feb", "mar"], # columns to unpivot
var_name="month",
value_name="sales",
)

pivot — long to wide

pivot is the inverse: spread a column's values into new columns. (Use pivot_table when there are duplicates to aggregate.)

repivot
wide = long.pivot(index="name", columns="month", values="sales")
# pivot_table aggregates duplicates; pivot errors on them
long.pivot_table(index="name", columns="month", values="sales", aggfunc="sum")

stack & unstack

stack pushes columns down into the index (wide→long); unstack pulls an index level up into columns (long→wide). They're the MultiIndex-aware cousins of melt/pivot:

rotate the axes
wide.stack() # columns → innermost index level (a long Series)
tall.unstack() # innermost index level → columns
grouped = df.groupby(["programme", "year"])["package"].mean()
grouped.unstack("year") # years become columns — a readable grid

Practice

Take a wide table (a value column per month) and melt it to tidy long form; confirm plotting/grouping is now natural. Then pivot it back to wide. Group by two keys and use unstack to turn the result into a grid.

Key takeaways

  1. 01Tidy (long) data — one variable per column, one observation per row — is what most tools expect.
  2. 02melt collapses many value columns into variable/value pairs (wide → long).
  3. 03pivot spreads values into columns (long → wide); pivot_table aggregates duplicates.
  4. 04stack moves columns into the index; unstack moves an index level into columns.
  5. 05unstack after a multi-key groupby turns a stacked result into a readable grid.