Sub topic 14
Summarizing groups with groupby and agg
This chapter assumes you can build a DataFrame, select columns, and filter rows with boolean masks. It also assumes you know how missing values (NaN) appear in a column. Here you will learn how groupby splits a table into groups and how agg turns each group into one summary row.
The split-apply-combine model
groupby works in three steps:
- Split the rows into groups that share a key value.
- Apply a function, such as a sum or a count, to each group.
- Combine the results into a new Series or DataFrame, with one row per group.
Calling df.groupby("region") computes nothing yet. It returns a lazy GroupBy object. The work happens when you call an aggregation on it.
Named aggregation
The clearest way to summarize is agg with keyword arguments. Each keyword 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.assign(pop_k=df["pop_m"] * 1000)
.groupby("region", as_index=False)
.agg(total_m=(“pop_m”, "sum"), n_cities=("city", "count"))
)
print(summary)Because the chain starts with assign, the original df is not changed. With as_index=False, region stays a normal column. Without it, region becomes the index of the result. Both forms are valid. Keeping a column is easier when you plan to merge the summary with another table later.
Choosing the function
You can pass a function name as a string ("sum", "mean", "min", "max", "count", "nunique") or a callable such as lambda s: s.max() - s.min(). Prefer strings when one exists, because pandas can run its faster built-in code for them.
Common errors
countversussize.countignoresNaNin the chosen column.sizecounts all rows in the group. If a column has missing values, the two give different numbers.- Missing keys disappear. By default, rows whose group key is
NaNare dropped. Passdropna=Falsetogroupbyto keep them as their own group. - Non-numeric columns. Calling
df.groupby("region").mean()on a table with text columns can raise aTypeErrorin current pandas. Select the columns first, or usenumeric_only=True. - Wrong syntax. A pair must be a tuple, like
("pop_m", "sum"). A bare string such as"pop_m"does not work as a named aggregation.
Several statistics at once
You can request many outputs from the same column, as long as each output name is different.
stats = df.groupby("region").agg(
mean_pop=("pop_m", "mean"),
max_pop=("pop_m", "max"),
cities=("city", "nunique"),
)
print(stats)Exercise
A DataFrame has a column score with one NaN in the group "A" (three rows in total in that group). What do ("score", "count") and ("score", "size") return for group "A" in a named aggregation, and why does size fail as a string there?
Show answer
count returns 2, because it skips the NaN. In a named aggregation, "size" is also accepted as a string and returns 3, because it counts every row in the group regardless of missing values. The two differ only when the column contains missing values.