pivot and pivot_table
What it is
pivot turns long data wide and requires index/column pairs to be unique; pivot_table aggregates duplicates instead of raising, with aggfunc and fill_value.
Why it matters
Models want one row per observation and one column per feature, while event data almost always arrives long.
In the real world: A sales table with one row per store per month becomes one row per store and one column per month: the layout finance expects in a spreadsheet.
Visual example
Reshapingpivot turns long data (one row per observation) into wide data (one column per feature).
Why this matters
Events arrive long; models read wide. Pivoting is the step between a log table and a feature matrix.
Common misconception
Wrong idea: pivot combines duplicate rows for you.
Correct idea: pivot raises on duplicates. pivot_table aggregates them — with the mean, unless you say otherwise.
- 1index=One output row per user.
- 2columns=One output column per metric.
- 3values=Each cell takes the matching value.
df.pivot(index="user_id", columns="metric", values="value")
df.pivot_table(
index="user_id", columns="event", values="id",
aggfunc="count", fill_value=0,
)Using pivot_table to dodge the duplicate error pivot raised. The error was information: the key you pivoted on was not what you thought it was.
Practise it: Pivot Event Counts, With the Zeros Included