Skip to main content
Albero Academy

Pivot Tables

Reshape long data into a grid — like an Excel pivot.

Aggregation & Combining8 min

A pivot table reshapes long data into a grid: one variable becomes the rows, another the columns, and a value fills the cells — the same idea as an Excel pivot, but reproducible in code.

pivot_table

rows × columns → aggregated values
df.pivot_table(
index="programme", # rows
columns="year", # columns
values="package", # cell values
aggfunc="mean", # how to aggregate collisions
)

The inverse: melt

melt does the opposite — turns wide columns back into long (tidy) rows, which most analysis and plotting prefer:

wide → long
pd.melt(df, id_vars=["name"], value_vars=["jan", "feb"],
var_name="month", value_name="sales")

Key takeaways

  1. 01pivot_table reshapes long data into a grid: index × columns → aggregated values.
  2. 02aggfunc decides how to combine multiple values per cell (mean, sum, count).
  3. 03melt is the inverse — wide columns back into tidy long rows.
  4. 04Analyse in long/tidy form; pivot to wide only for display.

Finished this chapter?

Mark it complete to track your progress through Pandas.