Sub topic 9
Faster groupby and merge patterns
This chapter assumes you know pandas groupby and merge, can read a short Python function, and have met the timing tools from earlier chapters. Group and join operations are often the slowest step in a pipeline. The usual causes are Python code running once per group, and joins that carry more data than they need.
Setup used in this chapter
The blocks below share this data. Run it first.
import numpy as np
import pandas as pd
from time import perf_counter
rng = np.random.default_rng(0)
n = 1_000_000
df = pd.DataFrame({
"region": rng.choice(["N", "S", "E", "W"], size=n),
"customer": rng.integers(0, 50_000, size=n),
"amount": rng.random(n),
})
customers = pd.DataFrame({
"customer": np.arange(50_000),
"segment": rng.choice(["retail", "trade", "online"], size=50_000),
"notes": "free text we do not need",
})Use built-in aggregations, not apply per group
groupby(...).apply(func) calls your Python function once per group. With 50,000 customers, that is 50,000 calls. Built-in aggregations such as sum, mean, and agg run in compiled code over all groups together.
start = perf_counter()
slow = df.groupby("customer")["amount"].apply(lambda s: s.sum())
print(f"apply: {perf_counter() - start:.3f}s")
start = perf_counter()
fast = df.groupby("customer")["amount"].sum()
print(f"sum: {perf_counter() - start:.3f}s")
pd.testing.assert_series_equal(slow, fast)The assertion confirms the results match. If you need several statistics, use named aggregation. It still runs in one pass:
stats = df.groupby("customer").agg(
total=("amount", "sum"),
average=("amount", "mean"),
orders=("amount", "size"),
)Use transform for group-level values on every row
A common task is to put a group statistic back next to each row, such as a row's share of its group total. Do not loop over groups or build a second frame and merge it back. transform returns a result aligned to the original rows.
sales = pd.DataFrame({
"region": ["N", "N", "S", "S"],
"amount": [10.0, 30.0, 20.0, 60.0],
})
sales["share"] = sales["amount"] / sales.groupby("region")["amount"].transform("sum")Group on categories with observed=True
Grouping by a category column is faster and uses less memory than grouping by strings. By default, though, pandas also reports category values that never appear in the data. With several category keys, this can create a large grid of empty combinations. Pass observed=True to keep only the groups that exist.
df["region"] = df["region"].astype("category")
by_region = df.groupby("region", observed=True)["amount"].sum()Make merges smaller and safer
A merge costs roughly in proportion to the size of both inputs and the width of the result. Three habits help:
- Select only the columns you need from the right-hand frame before merging.
- Make the key columns the same dtype on both sides. Joining an
int64key to a string orfloat64key forces slow conversions or returns no matches. - State the expected relationship with
validate. A key that is unexpectedly duplicated can multiply your rows and silently inflate totals.
merged = df.merge(
customers[["customer", "segment"]],
on="customer",
how="left",
validate="many_to_one",
)
print(merged.shape)Here validate="many_to_one" raises an error if customer repeats in customers. The notes column never enters the result, so it costs nothing.
Summary
- Prefer
agg,sum, and similar built-ins overgroupby.apply. - Use
transformfor group values that must line up with rows. - Use
observed=Truewhen grouping by categories. - Trim, align dtypes, and
validatebefore merging.
Exercise
A merge of orders onto a customers table returns more rows than the orders table had. Which merge argument would have caught this immediately, and what value would you pass?
Show answer
Pass validate="manytoone". It raises a MergeError if the customer key is duplicated in the right-hand table, which is the usual cause of extra rows.