Lesson 5 of 9 · 24m
groupby, transform, and Aggregations That Stay Readable
Split-apply-combine as a mental model, choosing agg/transform/apply correctly, and reshaping only when the output demands it.
groupby is where pandas starts feeling like a database query planner wearing Python clothes. The model is split-apply-combine: partition rows by keys, compute something per partition, then combine the result. The confusion comes from the word "something." Aggregation, transformation, and filtering produce different shapes and answer different questions.
agg reduces rows; transform preserves rows
per_customer = events.groupby("customer_id").agg(
revenue=("amount", "sum"),
orders=("order_id", "nunique"),
first_seen=("created_at", "min"),
)agg returns one row per group. Use it for metrics tables.
events["customer_total"] = events.groupby("customer_id")["amount"].transform("sum")
events["share_of_customer"] = events["amount"] / events["customer_total"]transform returns one value per original row. Use it for percentages of totals, z-scores within cohorts, ranks, and features in model training. Choosing the wrong one either drops rows you needed or broadcasts data you did not mean to duplicate.
apply is the escape hatch, not the default
apply is flexible because pandas hands each group to Python. That flexibility defeats much of the vectorized execution path and often hides a simpler primitive. Prefer named aggregations, built-in methods, transform, or reshaping. When you do need apply, keep the returned schema boring and test empty groups.
Multi-index output is a shape, not a nuisance
daily = events.groupby(["country", pd.Grouper(key="created_at", freq="D")])["amount"].sum()That result is a Series indexed by (country, day). You can keep it that way, or choose the shape explicitly:
daily_df = daily.reset_index()
wide = daily.unstack("country")reset_index() is the default move when the output is going into another pipeline. unstack/pivot is for human-readable matrices or model input. Do not pivot early just because wide data looks friendlier; long data joins, filters, and aggregates better.
Group keys are part of correctness
High-cardinality grouping keys explode memory. Timezone-naive keys split what should be one day. Floating-point keys group values you thought were equal. Treat grouping keys as data-model decisions: normalize them, bucket them deliberately, and count groups before running the expensive step.
Field notes
- Ask first: same number of rows, one row per group, or matrix? That selects transform, agg, or pivot.
- Named aggregation beats a column of lambdas for readability.
groupby(..., observed=True)avoids empty category combinations and saves memory.applyis a performance smell; use it when semantics require it, not because it is familiar.- Always inspect the resulting index; many downstream bugs are just unexpected MultiIndexes.
Was this lesson helpful?