Sub topic 14
Summarizing groups with groupby and agg
This chapter assumes you can build a DataFrame, select columns with [] and loc, and read a boolean mask. It also assumes you know how NaN appears in a column. The examples run on pandas 2.x.
The split-apply-combine model
groupby answers questions of the form "for each value of X, compute Y". It works in three steps:
- Split the rows into groups by the values of one or more key columns.
- Apply a function to each group independently, such as a sum, a count, or a custom function.
- Combine the per-group results into a new Series or DataFrame.
Calling df.groupby("region") does no computation. It returns a DataFrameGroupBy object that records how to split. Work happens only when you call an aggregation on it.
Named aggregation
The clearest way to summarize is named aggregation. Each keyword argument becomes an output column, and its value is a (column, function) pair.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
summary = (
df.groupby("region", as_index=False)
.agg(total_m=("pop_m", "sum"), n_cities=("city", "count"))
)
print(summary)The result has one row per region, sorted by region name: AS (3.1, 1), EU (3.5, 2), SA (10.7, 1). Function names are strings such as "sum", "mean", "min", "max", "count", "nunique", "first" and "last". Strings take pandas' optimized code paths, so prefer them over passing sum or np.sum.
Two shorter forms exist, and you will see them in older code:
df.groupby("region")["pop_m"].sum()gives a Series indexed by region.df.groupby("region")["pop_m"].agg(["min", "max"])gives a DataFrame with one column per function.
Named aggregation is usually better. It lets you aggregate several columns with different functions in one call, and the output names are ones you chose.
Custom functions
Any callable that takes a Series and returns a scalar works:
spread = df.groupby("region").agg(
spread_m=("pop_m", lambda s: s.max() - s.min())
)
print(spread)Python-level functions run once per group, so they are slower than built-in strings when there are many groups. Use a built-in whenever one exists.
as_index and the group keys
By default the group keys become the index of the result. With as_index=False they stay as a regular column, which is usually easier to merge or plot afterwards. You can get the same effect by calling .reset_index() on the result.
Grouping by several keys
Pass a list to group by combinations of values. The result then has a MultiIndex, unless you use as_index=False.
by_two = (
df.assign(big=df["pop_m"] > 3)
.groupby(["region", "big"], as_index=False)
.agg(total_m=("pop_m", "sum"))
)
print(by_two)Only combinations that occur in the data appear. EU contains only big=False, so there is no ("EU", True) row. If you need the missing combinations, reindex the result afterwards.
count, size, and missing values
Missing values affect groupby in two separate ways, and mixing them up is a common source of wrong totals.
sales = pd.DataFrame({
"store": ["A", "A", "B", "B", None],
"amount": [10.0, None, 5.0, 7.0, 3.0],
})
print(sales.groupby("store")["amount"].agg(["count", "size", "sum", "mean"]))
print(sales.groupby("store", dropna=False)["amount"].sum())The first call prints:
- Store A: count 1, size 2, sum 10.0, mean 10.0.
- Store B: count 2, size 2, sum 12.0, mean 6.0.
Compare the two kinds of missing data:
| Where the NaN is | Default behavior | How to change it |
|---|---|---|
| In a value column | Skipped by `sum`, `mean`, `min`, `max`, `count` | Fill it first with `fillna` if you want a different rule |
| In a key column | The row is dropped from every group | `dropna=False` keeps `NaN` as its own group |
count tallies non-missing values, while size tallies rows. Store A has two rows but only one non-missing amount, so its count is 1 and its size is 2. The mean of 10.0 divides by 1, not 2, because the missing value is skipped.
The row whose store is None appears in no group in the first call. The second call, with dropna=False, adds a NaN group whose sum is 3.0.
transform: results aligned to the original rows
agg reduces each group to one row. transform computes a per-group result but returns it with the same index as the input, so you can assign it back as a column.
df["region_total"] = df.groupby("region")["pop_m"].transform("sum")
df["share"] = (df["pop_m"] / df["region_total"]).round(2)
print(df[["city", "region", "share"]])Oslo gets 0.2 and Rome gets 0.8, because each is divided by the EU total. Lima and Pune each get 1.0 because they are alone in their regions. This pattern covers "share of group", "difference from the group mean", and "rank within the group". Each of these needs a group-level value placed next to every original row.
A related method, filter, keeps or drops whole groups. For example, df.groupby("region").filter(lambda g: len(g) > 1) returns only the rows from regions with more than one city.
Common errors and gotchas
- Aggregating a non-numeric column.
sumon a text column concatenates strings, andmeanon one raises aTypeError. Select the columns you want before aggregating, as indf.groupby("region")[["pop_m"]].mean(). - Wrong output name. In named aggregation the keyword is the new name and the tuple holds the source column. Writing
agg(pop_m=("total", "sum"))fails with aKeyErrorbecausetotalis not a column. - Expecting group order to follow the data. Keys are sorted by default. Pass
sort=Falseto keep the order of first appearance, which is also slightly faster. - Categorical keys. If the key column has the
categorydtype, pandas can report categories that have no rows. Passobserved=Trueto include only combinations that appear. This is a deliberate setting, because in pandas 2.x the default is stillFalseand emits aFutureWarning. - Aggregating after the fact. If you only need one statistic,
df.groupby("region")["pop_m"].sum()is shorter thanagg. Reach foraggwhen you need several outputs. - Passing
as_index=Falseand then indexing by key. After this option the key is a column, not an index label. Useresult.loc[result["region"] == "EU"]to find a row.
Exercises
Exercise
A DataFrame orders has columns customer, item and price. Write one expression that returns a DataFrame with columns customer, n_orders (number of rows per customer) and spent (sum of price), with customer as a regular column.
Show answer
orders.groupby("customer", asindex=False).agg(norders=("item", "size"), spent=("price", "sum")). Using "size" counts rows. Using ("item", "count") would count only non-missing items, which gives the same result unless item has NaN values.
Exercise
For the sales table above, why does sales.groupby("store")["amount"].sum() add up to 22.0 while sales["amount"].sum() gives 25.0? How do you make the grouped total match?
Show answer
The row with a missing store (amount 3.0) is dropped by groupby because its key is NaN, so the grouped sums are 10.0 + 12.0 = 22.0, while the whole column sums to 25.0. Passing dropna=False adds a NaN group with 3.0, and the grouped totals then also add up to 25.0.
Exercise
Using the cities DataFrame from this chapter, add a column vs_region_mean holding each city's pop_m minus the mean pop_m of its region. Which method do you use, and why not agg?
Show answer
df["vsregionmean"] = df["popm"] - df.groupby("region")["popm"].transform("mean"). The transform method returns one value per original row, aligned to df's index, so the subtraction and assignment work. agg would return one row per region, which cannot be subtracted row by row without a merge.