Sub topic 9
Faster groupby and merge patterns
This chapter assumes you can write a groupby and a merge in pandas, read basic NumPy-style column arithmetic, and have already met timing with perf_counter and vectorized operations from earlier chapters. Here you will learn which groupby and merge patterns are slow, why, and what to write instead.
The working model
Both groupby and merge are fast when pandas can do the whole job in compiled code. They get slow in three situations:
- A Python function runs once per group.
groupby(...).apply(func)callsfuncfor every group. With 50,000 groups that is 50,000 Python calls. - Extra data is carried along. A merge copies every column of both frames into the result, including columns you never use.
- The keys are awkward. Object (string) keys must be hashed as Python objects, and mismatched key dtypes force conversions or errors.
The fixes follow from this. Use built-in aggregations, keep the group-wise work inside pandas, shrink the frames before joining, and make the keys cheap to compare.
Prefer transform to apply or a manual merge
A common task is adding a group-level number to every row, such as each row's share of its region total. Beginners often aggregate, then merge the result back. transform does this in one step and keeps the original row order and index.
import pandas as pd
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")
print(sales)transform("sum") returns a Series the same length as sales, so the division lines up row by row. Passing the string name of a built-in lets pandas use its compiled path. Passing lambda s: s.sum() works but falls back to a Python call per group.
Use built-in aggregations instead of apply
apply is the most general groupby method, and the most expensive. Many apply calls compute something a built-in already provides. This example times both on 50,000 groups and checks that the answers match.
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({
"key": rng.integers(0, 50_000, n),
"value": rng.random(n),
})
start = perf_counter()
slow = df.groupby("key")["value"].apply(lambda s: s.sum() / len(s))
print(f"apply with lambda: {perf_counter() - start:.2f}s")
start = perf_counter()
fast = df.groupby("key")["value"].mean()
print(f"built-in mean: {perf_counter() - start:.2f}s")
pd.testing.assert_series_equal(slow, fast)Exact timings depend on your machine. The built-in is typically orders of magnitude faster here, because it makes no per-group Python calls.
When you need several statistics, use named aggregation. It computes them in one groupby and gives readable column names.
summary = df.groupby("key").agg(
total=("value", "sum"),
average=("value", "mean"),
rows=("value", "size"),
)
print(summary.head())When the logic is not a built-in
If your per-group logic seems to need apply, first try to express it with whole-column arithmetic before grouping. For example, to compute a weighted average per group, create a weighted column (value * weight), then sum weighted and weight with built-ins and divide the two results. Two compiled aggregations beat one Python function per group.
Group on cheap keys
Grouping by integers is faster than grouping by Python strings, and grouping by a category column is usually fast and memory-light. The previous chapter's dtype advice pays off here. Categorical keys carry a trap, though. By default pandas may return a row for every category, including categories that never occur in the data.
import pandas as pd
regions = pd.Categorical(["N", "S", "N"], categories=["N", "S", "E", "W"])
d = pd.DataFrame({"region": regions, "amount": [1.0, 2.0, 3.0]})
print(d.groupby("region", observed=True)["amount"].sum())With observed=True the result has only the rows for N and S. Without it, the default in current pandas 2.x releases, you also get rows for E and W with a sum of 0. That is extra work, and it can surprise you when several categorical keys multiply into many empty combinations. Recent pandas versions warn that the default will change, so set observed explicitly.
Two more options reduce work:
sort=Falseskips sorting the group keys. Use it when you do not need ordered output.dropna=Falsekeeps groups whose key is missing. Leave it at the default unless you need those rows.
Make merges cheaper
A merge does three things: align keys, match rows, and copy columns into a new frame. You can reduce each.
Shrink both sides first
Select only the columns you need, and filter rows before joining, not after. The customers table below has a wide notes column that the merge does not need.
import pandas as pd
orders = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"customer_id": [10, 11, 10, 12],
"amount": [25.0, 40.0, 15.0, 60.0],
})
customers = pd.DataFrame({
"customer_id": [10, 11, 12],
"region": ["N", "S", "N"],
"notes": ["long text"] * 3,
})
merged = orders.merge(
customers[["customer_id", "region"]],
on="customer_id",
how="left",
validate="many_to_one",
)
print(merged)Validate the relationship
The validate="many_to_one" argument asserts that customer_id is unique in the right frame. This protects you from the most expensive merge bug: duplicate keys on the right silently multiply rows. A row count that grows after a merge means a slower result and usually a wrong one.
dup_customers = pd.DataFrame({
"customer_id": [10, 10, 11],
"region": ["N", "N", "S"],
})
try:
orders.merge(dup_customers, on="customer_id", validate="many_to_one")
except pd.errors.MergeError as err:
print("Caught:", err)Aggregate before you join
If you only need totals from the large side, aggregate first and merge the small result. Joining 1,000,000 order rows to a customer table and then grouping does far more work than grouping first and joining one row per customer.
per_customer = orders.groupby("customer_id", as_index=False)["amount"].sum()
report = per_customer.merge(customers[["customer_id", "region"]], on="customer_id")
print(report)Use a lookup instead of a merge for one column
When you only add a single column from a table with unique keys, map against an indexed Series is simple and avoids building a new frame.
region_by_customer = customers.set_index("customer_id")["region"]
orders["region"] = orders["customer_id"].map(region_by_customer)
print(orders)The lookup Series must have a unique index. If the index has duplicates, map raises an error. That is a useful check, equivalent to the validate argument above.
Match key dtypes
Merging an integer key against a string key raises a ValueError, and keys of different but compatible dtypes can force conversions. Convert both sides to the same dtype once, before the merge. If the same key is used in many merges, convert it once and keep it.
orders["customer_id"] = orders["customer_id"].astype("int64")
customers["customer_id"] = customers["customer_id"].astype("int64")Common errors and checks
| Symptom | Likely cause | Fix |
|---|---|---|
| Groupby takes seconds on many groups | `apply` or a lambda in `agg` | Use a built-in name such as `"mean"` or `"sum"` |
| Result has rows with zero counts | Categorical key, `observed=False` | Pass `observed=True` |
| Row count grows after merge | Duplicate keys on one side | Use `validate=` and deduplicate the keys |
| `ValueError` on merge | Key dtypes differ, such as int and object | Convert both keys to one dtype |
| Merge uses lots of memory | Unneeded columns carried along | Select columns before merging |
Every rewrite in this chapter should be checked as in the verification chapter. Compare the old and new results with pd.testing.assert_series_equal or assert_frame_equal. Rewrites that change the index or the row order are a frequent source of false differences, so call sort_values and reset_index(drop=True) on both sides before comparing when order is not part of the contract.
Exercise
A pipeline runs df.groupby("customer")["amount"].apply(lambda s: s.max() - s.min()) and takes 8 seconds with 200,000 groups. Describe a faster version, and say how you would confirm that it returns the same result.
Show answer
Aggregate once with built-ins and subtract the results: g = df.groupby("customer")["amount"]; fast = g.max() - g.min(). Both calls run in compiled code, so there is no Python function call per group. Another option is g.agg(["max", "min"]) followed by a subtraction. To confirm equality, run both versions and compare them with pd.testing.assert_series_equal(slow, fast, check_names=False). The check_names=False argument is needed because the subtraction result may have a different Series name from the apply result. Time both with perf_counter to confirm the gain.
Exercise
After adding a left merge of orders with customers, the result has more rows than orders. What is the most likely cause, and which argument would have caught it?
Show answer
The customers frame has duplicate values in the key column, so each matching order row is repeated once per duplicate. Passing validate="many_to_one" to merge raises a MergeError when the right key is not unique. Deduplicating customers on the key, with drop_duplicates("customer_id") or by fixing the source data, resolves the problem.