Reference · Python (pandas)
Pivot long data to wide in Python (pandas)
Spread a key column into declared columns, one row per index, leaving absent combinations missing.
When to use it
Monthly or category readings that a report needs side by side.
How
pivot (or pivot_table with an explicit aggfunc), then reindex to the declared columns.
df.pivot(index="entity", columns="month", values="value").reindex(columns=["Jan", "Feb", "Mar"])
- pivot raises on duplicate index/column pairs; decide the collision rule first.
Pitfalls
- Filling gaps with zero.
- Letting each batch decide the columns.
Lesson: Pivot without inventing zeros
Practise it: Pivot monthly values, keeping zeros and gaps apart