Sub topic 4
Aggregating with built-in functions
This chapter assumes you can build a DataFrame, select columns from it, and read a Series with a named index. It also assumes you have seen df.groupby("region") create a GroupBy object. Here you will use the built-in aggregation methods on that object, see how they treat missing values and column types, and learn the first/last/nth distinction.
What an aggregation does
An aggregation reduces each group to one value per column. Five rows in two groups become two values per column, whatever the group sizes. This is the "apply" step of split-apply-combine, where the applied function is a reducer.
The examples below use this DataFrame.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})The common reducers
Each of these is a method on the GroupBy object.
| Method | Result per group | Notes |
|---|---|---|
| `sum()` | Total of the values | Concatenates strings. An all-missing group gives 0. |
| `mean()` | Arithmetic mean | Always floating point. Fails on text columns. |
| `min()`, `max()` | Smallest and largest value | Work on text and dates too. |
| `median()` | Middle value | Same as `quantile(0.5)`. |
| `std()`, `var()` | Sample standard deviation and variance | Use `ddof=1` by default, so a one-row group gives NaN. |
| `nunique()` | Number of distinct values | Ignores missing values unless `dropna=False`. |
| `first()`, `last()` | First or last non-missing value | Depends on the current row order. |
| `prod()` | Product of the values | Rarely needed. |
| `any()`, `all()` | Boolean reduction | For boolean or truthy columns. |
Summing and averaging
Select the columns you want before calling the method. Selecting a single column returns a Series. Selecting a list of columns returns a DataFrame.
print(df.groupby("region")[["units", "revenue"]].sum())
# units revenue
# region
# North 15 175.0
# South 18 220.0
print(df.groupby("region")["revenue"].mean())
# region
# North 87.500000
# South 73.333333
# Name: revenue, dtype: float64The dtype follows the same rules as the ungrouped methods. sum of integers stays an integer, and mean always returns a float.
Minimum, maximum, and distinct counts
g = df.groupby("region")
print(g["units"].min())
# region
# North 5
# South 3
# Name: units, dtype: int64
print(g["units"].max())
# region
# North 10
# South 8
# Name: units, dtype: int64
print(g["product"].nunique())
# region
# North 2
# South 2
# Name: product, dtype: int64nunique counts distinct values, not rows. South has three rows but only two distinct products. This makes it the right tool for questions such as "how many different customers bought in each region". Counting rows is a different operation, covered in the next chapter.
first and last
first() returns the first non-missing value in each group, and last() returns the last. "First" means first in the current row order, so sort before grouping if order matters.
print(g["revenue"].first())
# region
# North 100.0
# South 70.0
# Name: revenue, dtype: float64
print(g["revenue"].last())
# region
# North 75.0
# South 120.0
# Name: revenue, dtype: float64The "non-missing" part is easy to miss. Both methods skip NaN, so the result can come from a different row for each column.
gaps = pd.DataFrame({"k": ["a", "a", "b"], "v": [None, 5.0, None]})
print(gaps.groupby("k")["v"].first())
# k
# a 5.0
# b NaN
# Name: v, dtype: float64Group a returns 5.0 even though its first row holds NaN. Group b has no non-missing value, so it returns NaN.
Missing values inside the data
Reducers skip missing values by default, as they do on an ungrouped Series. A group made entirely of missing values is where the methods differ.
data = pd.DataFrame({"k": ["a", "a", "b"], "v": [None, None, 3.0]})
g2 = data.groupby("k")["v"]
print(g2.sum())
# k
# a 0.0
# b 3.0
# Name: v, dtype: float64
print(g2.sum(min_count=1))
# k
# a NaN
# b 3.0
# Name: v, dtype: float64
print(g2.mean())
# k
# a NaN
# b 3.0
# Name: v, dtype: float64Group a has no data, but sum() reports 0.0. Because 0.0 looks like a real total, this can hide gaps in a report. Pass min_count=1 when an empty group should be NaN. mean has no such ambiguity, since dividing zero values by zero gives NaN.
Column selection and non-numeric columns
If you call a reducer on the whole GroupBy without selecting columns, pandas tries every non-key column.
print(df.groupby("region").sum())
# product units revenue
# region
# North AB 15 175.0
# South AAB 18 220.0The product column was concatenated as text. The output has no error, but the values are meaningless. mean() on the same object raises a TypeError because strings cannot be averaged.
Two habits avoid this:
- Select the columns you want first:
df.groupby("region")[["units", "revenue"]].sum(). - Pass
numeric_only=Truewhen you want pandas to drop text columns for you:df.groupby("region").mean(numeric_only=True).
The first habit is better in scripts. It documents which columns you expect and fails loudly if one is renamed.
Method names versus Python functions
agg and its relatives accept function names as strings, such as "sum", or callables. Prefer the strings, which pandas maps to its fast implementations.
print(df.groupby("region")["units"].agg("sum"))
# region
# North 15
# South 18
# Name: units, dtype: int64Passing the Python built-in sum or max still works in many versions. Recent pandas releases emit a FutureWarning for it, because the built-in and the pandas method can differ in how they treat missing values. The string name is stable.
Choosing a reducer
- Use
sumfor additive quantities such as units or revenue. - Use
meanormedianfor typical values. Prefermedianwhen a few extreme rows would distort a mean. - Use
minandmaxfor ranges, earliest and latest dates, or alphabetical bounds. - Use
nuniquefor "how many different X". Usefirstorlastwhen every row in a group repeats the same attribute and you want it once, such as a customer's country. - Use
stdonly on groups with at least two rows. One-row groups give NaN.
Exercise
A DataFrame has a column score where every value in group "x" is NaN. What do groupby("k")["score"].sum() and groupby("k")["score"].mean() return for group "x", and how do you make sum return NaN instead?
Show answer
sum() returns 0.0 for group "x" and mean() returns NaN. Call sum(min_count=1) so a group with fewer than one valid value returns NaN.
Exercise
Write a call that returns, for each region in the df above, the number of distinct products and the highest revenue, using only methods from this chapter. Why can't one single method call return both?
Show answer
Call df.groupby("region")["product"].nunique() and df.groupby("region")["revenue"].max() as two separate expressions. Each reducer method applies one function, so a single call cannot give two different functions on two columns. The next chapters cover agg, which lets you combine them in one call.