Sub topic 4
Aggregating with built-in functions
This chapter assumes you can build a DataFrame, select columns, and read a Series with an index. It also assumes you know that df.groupby("region") creates a GroupBy object. That object holds the groups and does no calculation until you ask for one.
What an aggregation does
An aggregation reduces each group to a single value per column. After you call one, the result has one row per group. The group keys become the index.
The examples 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],
})
totals = df.groupby("region")["revenue"].sum()
print(totals)
# region
# North 175.0
# South 220.0
# Name: revenue, dtype: float64Selecting ["revenue"] before .sum() gives a Series. Selecting with a list, [["units", "revenue"]], gives a DataFrame with one column per selected column.
print(df.groupby("region")[["units", "revenue"]].sum())
# units revenue
# region
# North 15 175.0
# South 18 220.0The common built-in functions
These methods work on a GroupBy or on a column selected from one.
| Method | Result for each group |
|---|---|
| `sum()` | Total of the values |
| `mean()` | Average of the values |
| `min()` / `max()` | Smallest / largest value |
| `nunique()` | Number of distinct values |
| `first()` / `last()` | First / last non-missing value in row order |
g = df.groupby("region")
print(g["units"].mean())
# region
# North 7.5
# South 6.0
# Name: units, dtype: float64
print(g["revenue"].max())
# region
# North 100.0
# South 120.0
# Name: revenue, dtype: float64
print(g["product"].nunique())
# region
# North 2
# South 2
# Name: product, dtype: int64
print(g["product"].first())
# region
# North A
# South A
# Name: product, dtype: objectnunique works on any column type. first depends on row order, so sort the data first if "first" must mean something specific, such as the earliest date.
Missing values
Most of these functions skip missing values. sum treats a group of all-missing values as 0, and mean returns NaN for such a group. If you need NaN from an all-missing sum, pass min_count=1.
data = pd.DataFrame({"k": ["a", "a", "b"], "v": [1.0, None, None]})
print(data.groupby("k")["v"].sum())
# k
# a 1.0
# b 0.0
# Name: v, dtype: float64
print(data.groupby("k")["v"].sum(min_count=1))
# k
# a 1.0
# b NaN
# Name: v, dtype: float64Common errors
- Aggregating every column.
df.groupby("region").mean()tries to average the text columnproductand raises aTypeError.sum()would instead join the strings, giving"AB". Select the columns you want first, or passnumeric_only=Trueto functions that accept it. - Forgetting the aggregation.
df.groupby("region")["revenue"]returns a GroupBy object, not numbers. Printing it shows only an object description. - Reading the index as data. The group keys are in the index. To use them as ordinary columns, see the chapter on result shape.
Exercise
Using the DataFrame above, which expression returns the number of distinct products sold in each region?
Show answer
df.groupby("region")["product"].nunique(). It returns 2 for North and 2 for South.