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
df.pivot_table(index="programme", # rowscolumns="year", # columnsvalues="package", # cell valuesaggfunc="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:
pd.melt(df, id_vars=["name"], value_vars=["jan", "feb"],var_name="month", value_name="sales")
Key takeaways
- 01pivot_table reshapes long data into a grid: index × columns → aggregated values.
- 02aggfunc decides how to combine multiple values per cell (mean, sum, count).
- 03melt is the inverse — wide columns back into tidy long rows.
- 04Analyse in long/tidy form; pivot to wide only for display.
