Reshaping Data (pivot, pivot_table, melt)
Long vs wide (why reshaping exists)
Section titled “Long vs wide (why reshaping exists)”- Long format: one row per observation (better for analysis/plotting)
- Wide format: values spread across columns (good for reporting)
Example: long format
Section titled “Example: 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: reshape when data is unique
Section titled “pivot: reshape when data is unique”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: reshape with aggregation
Section titled “pivot_table: reshape with aggregation”wide = df.pivot_table(index="date", columns="city", values="sales", aggfunc="sum")
print(wide)melt: wide → long
Section titled “melt: wide → long”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)Practical notes
Section titled “Practical notes”- Many ML/EDA workflows prefer long format.
- Pivoted tables often have a multi-index for columns—use
reset_index()orwide.columnsrenaming if needed.
Visualize it
Section titled “Visualize it”flowchart LR W["Wide format
(one column per city)"] -->|"melt()"| L["Long format
(one row per observation)"] L -->|"pivot() / pivot_table()"| W
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Melt Wide to Long
Section titled “Exercise 1 – Melt Wide to Long”Exercise 2 – Pivot Long Back to Wide
Section titled “Exercise 2 – Pivot Long Back to Wide”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.coffeeCtapch.feedbackHeading
pch.feedbackSubheading