ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Pandas Tutorial• 7 min read

Reshaping: pivot_table(), melt() & stack/unstack

Converting between wide and long data formats for analysis and visualization

Pivoting and melting reshape tabular data between Wide format (columns for each variable) and Long format (tidy rows with key-value pairs).

pivot_table() vs melt()

df.pivot_table(index=..., columns=..., values=..., aggfunc=...): Spreads categorical values into separate column headers, computing aggregated summaries (identical to Excel Pivot Tables).

pd.melt(df, id_vars=[...], value_vars=[...]): Unpivots wide columns into clean long tidy rows, essential for plotting with Seaborn or ggplot.

Building a Dynamic Pivot Table
import pandas as pd

data = {
    "year": [2023, 2023, 2024, 2024],
    "category": ["Hardware", "Software", "Hardware", "Software"],
    "sales": [45000, 32000, 58000, 41000]
}
df = pd.DataFrame(data)

# Create 2D pivot table comparing sales by year and category
pivot = df.pivot_table(index="year", columns="category", values="sales", aggfunc="sum")
print("Pivot Table Report:
", pivot)
pivot_table cross-tabulates data along multi-dimensional indices.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which Pandas function "unpivots" a wide DataFrame with multiple metric columns into a tidy long format?