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:
# 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:
long = wide.melt(id_vars=["name"], # columns to keep as-isvalue_vars=["jan", "feb", "mar"], # columns to unpivotvar_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.)
wide = long.pivot(index="name", columns="month", values="sales")# pivot_table aggregates duplicates; pivot errors on themlong.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:
wide.stack() # columns → innermost index level (a long Series)tall.unstack() # innermost index level → columnsgrouped = 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
- 01Tidy (long) data — one variable per column, one observation per row — is what most tools expect.
- 02melt collapses many value columns into variable/value pairs (wide → long).
- 03pivot spreads values into columns (long → wide); pivot_table aggregates duplicates.
- 04stack moves columns into the index; unstack moves an index level into columns.
- 05unstack after a multi-key groupby turns a stacked result into a readable grid.
