Sub topic 15
Pitfalls and performance
This chapter collects the groupby mistakes that cause wrong numbers or slow code. It assumes you know agg, transform, filter, apply, as_index, and dropna from the earlier chapters. Examples target pandas 2.x. Where pandas 3.0 changes a default, the text says so.
A quick map of the risks
| Symptom | Likely cause | Fix |
|---|---|---|
| Rows of zeros or NaN for groups that do not exist in your data | Categorical key with `observed=False` | Pass `observed=True` |
| `TypeError` from `mean` or `sum` on a mixed-type frame | Non-numeric columns are included | Select columns first, or use `numeric_only=True` |
| Some rows silently missing from the result | Missing group keys are dropped | Use `dropna=False` if you need them |
| Group counts that look too small | `count` skips missing values | Use `size` to count rows |
| Code takes seconds or minutes on large data | Python function called once per group or per row | Use built-in aggregation names |
| Warning about grouping columns inside `apply` | `apply` passes the key columns to your function | Pass `include_groups=False` |
Categorical keys and unobserved groups
A categorical column knows all its possible values, even ones that never appear in the data. With observed=False, groupby produces a result row for every category.
import pandas as pd
sizes = pd.Categorical(["S", "M", "S"], categories=["S", "M", "L"])
orders = pd.DataFrame({"size": sizes, "qty": [1, 2, 3]})
print(orders.groupby("size", observed=False)["qty"].sum())
# size
# S 4
# M 2
# L 0
# Name: qty, dtype: int64
print(orders.groupby("size", observed=True)["qty"].sum())
# size
# S 4
# M 2
# Name: qty, dtype: int64In pandas 2.x the default is observed=False, and omitting the argument with a categorical key emits a FutureWarning. In pandas 3.0 the default becomes True. Set it explicitly so your code gives the same result on both versions.
Choose by purpose. Use observed=False when you want a complete report, such as a table with every size listed, including zeros. Use observed=True otherwise.
The cost matters more with several categorical keys. With observed=False, pandas builds the full Cartesian product of categories. Two keys with 1,000 categories each give a million result rows, nearly all empty. If a groupby on categoricals is surprisingly slow or uses a lot of memory, check this first.
Categorical keys have two more effects:
- Groups come out in category order, not alphabetical order. Define categories in the order you want them reported.
- A categorical key can speed up grouping on a column with many repeated strings, because pandas groups on small integer codes instead of comparing strings.
Mixed-type columns
Calling an aggregation on the whole frame includes every column. If one is text, mean raises a TypeError in pandas 2.x. There are two fixes.
import pandas as pd
people = pd.DataFrame({
"team": ["a", "a", "b"],
"name": ["Ana", "Bo", "Cy"],
"score": [1.0, 2.0, 6.0],
})
# Preferred: choose the columns you mean.
print(people.groupby("team")["score"].mean())
# Alternative: let pandas drop non-numeric columns.
print(people.groupby("team").mean(numeric_only=True))Selecting columns is better than numeric_only=True. It states your intent, and it keeps an unexpected numeric column, such as an ID stored as an integer, from being averaged by accident. Selecting also does less work, because pandas skips the columns you do not need.
Missing values: keys versus data
Two kinds of missing values behave differently, and mixing them up causes wrong totals.
- A missing group key drops that row from the result unless you pass
dropna=False. - A missing value in an aggregated column is skipped by
sum,mean,min,max, andcount.
Two consequences follow. A groupby total can be smaller than the column total because rows with missing keys vanished. Use size when you want the number of rows and count when you want the number of non-missing values.
A quick check catches the first problem:
import pandas as pd
df = pd.DataFrame({"k": ["a", None, "a"], "v": [1, 2, 3]})
grouped_total = df.groupby("k")["v"].sum().sum()
print(grouped_total, df["v"].sum())
# 4 6If the two numbers differ, some rows had missing keys. Decide whether to drop them on purpose, fill the key with a placeholder such as "unknown", or use dropna=False.
Slow code: choosing the fast path
Groupby is fast when pandas can run a built-in aggregation in compiled code over all groups at once. It is slow when it must call a Python function once per group, or worse, once per row. The cost grows with the number of groups, because each call has fixed overhead.
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
big = pd.DataFrame({
"key": rng.integers(0, 1000, 200_000),
"x": rng.random(200_000),
})
t0 = time.perf_counter()
slow = big.groupby("key")["x"].apply(lambda s: s.sum())
t1 = time.perf_counter()
fast = big.groupby("key")["x"].sum()
t2 = time.perf_counter()
pd.testing.assert_series_equal(slow, fast)
print(f"apply with lambda: {t1 - t0:.4f}s")
print(f"built-in sum: {t2 - t1:.4f}s")Both versions return the same result, and the assertion confirms it. The exact times depend on your machine. The built-in version is normally much faster, and the gap widens as the number of groups grows.
The same rule applies to transform. Pass the function name as a string.
# Fast: compiled path
big["group_total"] = big.groupby("key")["x"].transform("sum")
# Slower: calls a Python function for each group
big["group_total_slow"] = big.groupby("key")["x"].transform(lambda s: s.sum())Use this order of preference:
- A built-in method or its string name:
sum,mean,max,nunique,first,cumsum,rank,shift. - Vectorized arithmetic on the output of a built-in. For example, compute a share as
df["revenue"] / df.groupby("region")["revenue"].transform("sum"). aggortransformwith a custom function, when no built-in fits.apply, when the logic needs the whole sub-DataFrame at once.
Replacing apply with faster idioms
Many apply calls can be rewritten. To get the row with the largest revenue in each region, avoid apply and use idxmax.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
best = df.loc[df.groupby("region")["revenue"].idxmax()]
print(best)
# region product revenue
# 0 North A 100.0
# 4 South B 120.0Likewise, filter with a lambda can often become a boolean mask:
units = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"units": [10, 5, 7, 3, 8],
})
mask = units.groupby("region")["units"].transform("sum") > 15
big_regions = units[mask]This computes the group sum once with the fast path, then filters with an ordinary boolean index.
Grouping columns inside apply
When you call apply on a DataFrameGroupBy, pandas passes each group with the key columns included. Since pandas 2.2, operating on those columns emits a DeprecationWarning, and pandas 3.0 removes them from the passed groups. Write the call so it works on both:
top2 = df.groupby("region").apply(
lambda g: g.nlargest(2, "revenue"),
include_groups=False,
)Inside the function, g has no region column. If your logic needs the key, read it from g.name.
Also avoid mutating the group inside apply. Return a new object instead. Modifying g in place can give inconsistent results and, in pandas 2.x, may trigger copy-on-write warnings.
Smaller performance habits
- Pass
sort=Falsewhen you do not need ordered groups. Sorting the keys has a cost, and it grows with the number of groups. Groups then appear in order of first occurrence. - Select the columns to aggregate before the aggregation, as in
df.groupby("k")[["a", "b"]].sum(). - Do not loop over a GroupBy object to build a summary. Iteration is fine for inspecting a few groups, but it calls Python code per group.
- Do not call
groupbyrepeatedly on the same keys. Store the object withg = df.groupby("key")and reuse it. The grouping computation is cached on the object, so the second aggregation skips that work. - Group by integer or categorical keys instead of long strings when you can.
Exercise
A DataFrame has a categorical column tier with categories ["gold", "silver", "bronze"]. No row has tier == "bronze". You run df.groupby("tier", observed=False)["spend"].sum(). What does the result contain for "bronze", and what do you change to leave it out? Separately, you call df.groupby("user")["spend"].transform(lambda s: s.sum()) on 5 million rows with many users. What is a faster call?
Show answer
The result contains a "bronze" row with a sum of 0, because observed=False reports every category. Pass observed=True to leave it out (and to get the same behavior on pandas 3.0). For the second question, use df.groupby("user")["spend"].transform("sum"). The string name uses the compiled path instead of calling a Python function for every group.