Skip to content

Reshaping Data (pivot, pivot_table, melt)

  • Long format: one row per observation (better for analysis/plotting)
  • Wide format: values spread across columns (good for reporting)
Long format
import pandas as pd
 
df = pd.DataFrame({
    "date": ["2025-01-01", "2025-01-01", "2025-01-02", "2025-01-02"],
    "city": ["pune", "delhi", "pune", "delhi"],
    "sales": [100, 120, 90, 150],
})
 
print(df)
pivot
wide = df.pivot(index="date", columns="city", values="sales")
print(wide)

If the combination of (index, columns) isn’t unique, pivot throws an error.

pivot_table
wide = df.pivot_table(index="date", columns="city", values="sales", aggfunc="sum")
print(wide)
melt
wide = pd.DataFrame({
    "date": ["2025-01-01", "2025-01-02"],
    "pune": [100, 90],
    "delhi": [120, 150],
})
 
long = wide.melt(id_vars=["date"], var_name="city", value_name="sales")
print(long)
  • Many ML/EDA workflows prefer long format.
  • Pivoted tables often have a multi-index for columns—use reset_index() or wide.columns renaming if needed.
diagram Wide vs long, and how to move between them mermaid
melt turns wide columns into long rows; pivot/pivot_table turns long rows back into wide columns.
sketch Wide table <-> long table p5.js
melt stacks columns into rows; pivot spreads rows back out into columns. Same data, two shapes.

Exercise 3 – Aggregate Duplicates With pivot_table

Section titled “Exercise 3 – Aggregate Duplicates With pivot_table”

Reshaping assumes your tables are already combined — continue to Merging and Joining Data (merge, join, concat) for how to bring multiple tables together in the first place.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading