Sub topic 6
Several aggregations at once with agg and named aggregation
A single groupby(...).sum() answers one question. Most summary tables need several answers per group: a total, an average, a count of distinct items. The agg method (short for aggregate) computes them in one call. This chapter covers its input forms, how each shapes the result, and how named aggregation gives you flat, readable output.
This chapter assumes you can create a DataFrame, select columns, and read a Series with an index. It also assumes you know what a GroupBy object is. Every example uses 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 three input forms of agg
agg accepts a function name, a list, a dict, or keyword arguments. The input form decides the shape of the output columns.
| Form | Example | Resulting columns |
|---|---|---|
| One name or function | `.agg("sum")` | Same as the input columns |
| List of functions | `.agg(["sum", "mean"])` | One column per function (a MultiIndex if applied to several columns) |
| Dict of column to function(s) | `.agg({"units": "sum"})` | One column per dict entry (a MultiIndex when a value is a list) |
| Keywords of `(column, function)` | `.agg(total=("units", "sum"))` | One flat column per keyword |
A list of functions on one column
Select one column first, then pass a list. You get one result column per function, named after the function.
stats = df.groupby("region")["revenue"].agg(["sum", "mean", "max"])
print(stats)
# sum mean max
# region
# North 175.0 87.500000 100.0
# South 220.0 73.333333 120.0Strings such as "sum" and "mean" are the preferred way to name built-in aggregations. You can also pass the callable (sum, np.mean), but pandas has to map it to the built-in implementation. A plain Python callable that pandas does not recognize is slower, because it runs once per group in Python.
A dict of columns to functions
A dict lets you choose different functions for different columns.
mixed = df.groupby("region").agg({
"units": "sum",
"revenue": ["mean", "max"],
})
print(mixed)
# units revenue
# sum mean max
# region
# North 15 87.500000 100.0
# South 18 73.333333 120.0Because revenue received a list, the columns are now a two-level MultiIndex. Each column is a tuple like ("revenue", "mean"). You select it with mixed[("revenue", "mean")]. Many people find this awkward. One workaround is to flatten the labels:
mixed.columns = ["_".join(col) for col in mixed.columns]
print(mixed.columns.tolist())
# ['units_sum', 'revenue_mean', 'revenue_max']Flattening works, but named aggregation produces flat columns directly.
Named aggregation
Named aggregation is the form you will use most. Each keyword argument is the name you want in the output. Each value is a (column, function) pair.
summary = df.groupby("region").agg(
total_units=("units", "sum"),
avg_revenue=("revenue", "mean"),
n_products=("product", "nunique"),
)
print(summary)
# total_units avg_revenue n_products
# region
# North 15 87.500000 2
# South 18 73.333333 2Three properties make this form convenient:
- The output columns are flat, so there is no MultiIndex to flatten.
- The output order follows the order of your keywords.
- You can use the same input column more than once. For example,
lo=("revenue", "min")andhi=("revenue", "max")can appear in the same call.
The tuple is a plain tuple, but pandas also provides pd.NamedAgg, which makes the intent explicit:
summary2 = df.groupby("region").agg(
total_units=pd.NamedAgg(column="units", aggfunc="sum"),
avg_revenue=pd.NamedAgg(column="revenue", aggfunc="mean"),
)The two spellings behave identically. Use NamedAgg when you want self-documenting code, and plain tuples when you want brevity.
Names that are not valid Python identifiers
Keyword arguments must be valid identifiers, so total revenue is not allowed as a keyword. Unpack a dict instead:
labeled = df.groupby("region").agg(**{
"Total revenue": ("revenue", "sum"),
"Distinct products": ("product", "nunique"),
})
print(labeled)
# Total revenue Distinct products
# region
# North 175.0 2
# South 220.0 2Custom functions inside agg
Any function that takes a Series and returns a single value can be used as an aggregation. In named aggregation, a lambda is convenient because the keyword supplies the output name:
report = df.groupby("region").agg(
total_revenue=("revenue", "sum"),
revenue_range=("revenue", lambda s: s.max() - s.min()),
first_product=("product", "first"),
)
print(report)
# total_revenue revenue_range first_product
# region
# North 175.0 25.0 A
# South 220.0 90.0 AThe function receives one group's values for the named column, as a Series. It must reduce them to one scalar. If it returns a Series or a list, pandas raises an error such as ValueError: Must produce aggregated value.
Duplicate lambda names in a list
In the list form, pandas names the output column after the function. A lambda's name is <lambda>, so two lambdas collide:
# Raises SpecificationError: Function names must be unique
# df.groupby("region")["revenue"].agg([lambda s: s.min(), lambda s: s.max()])Give each function a name by passing (name, function) tuples:
spread = df.groupby("region")["revenue"].agg([
("lowest", lambda s: s.min()),
("highest", lambda s: s.max()),
])
print(spread)
# lowest highest
# region
# North 75.0 100.0
# South 30.0 120.0Alternatively, define regular functions with def, since their __name__ is used as the column label. For a single-column result, named aggregation is usually the clearer choice.
Combining agg with result shape options
Named aggregation works with the shape controls from the previous chapter. With as_index=False, the group keys remain ordinary columns:
flat = df.groupby(["region", "product"], as_index=False).agg(
units=("units", "sum"),
revenue=("revenue", "sum"),
)
print(flat)
# region product units revenue
# 0 North A 10 100.0
# 1 North B 5 75.0
# 2 South A 10 100.0
# 3 South B 8 120.0Calling .reset_index() on the default result gives the same table.
Common errors
- Selecting a missing column. Naming a column that does not exist, as in
("revnue", "sum"), raises aKeyError. Check the spelling. - Mixing styles in one call. You cannot pass a positional dict and keyword arguments together. Pick one form.
- Old dict-of-dict renaming. Passing
{"revenue": {"total": "sum"}}to a column selection was removed in pandas 1.0 and now raises an error. Use named aggregation instead. - A non-reducing function. A function such as
lambda s: s.sort_values()returns many values per group. That is a job forapplyortransform, which later chapters cover. - Mean on text columns.
.agg("mean")on a DataFrame that contains string columns can raise aTypeError. Select the numeric columns first, or use named aggregation so each column gets an appropriate function.
Choosing a form
Use the list form for a quick look at one column. Use the dict form when you already hold a mapping from columns to functions, for example from a configuration. Use named aggregation for any table you intend to keep, share, or build on, because its column names are explicit and flat.
Exercise
Using the df defined at the start of this chapter, write one groupby call that returns a table indexed by product with three flat columns: n_rows (the number of rows, counted as non-missing values in the units column), max_units (the largest units value), and avg_price (the mean of revenue divided by units is not needed; just use the mean of revenue). Which form of agg do you use, and why?
Show answer
Use named aggregation: df.groupby("product").agg(n_rows=("units", "count"), max_units=("units", "max"), avg_price=("revenue", "mean")). Named aggregation gives flat, named columns directly. A dict with list values would give MultiIndex columns that need flattening. For product A the result is nrows 3, maxunits 10, avgprice 66.666667. For product B it is nrows 2, maxunits 8, avgprice 97.5.
Exercise
Why does df.groupby("region")["revenue"].agg([lambda s: s.min(), lambda s: s.max()]) fail, and how do you fix it while keeping a list?
Show answer
Both lambdas have the name <lambda>, so pandas would give two output columns the same label and raises a SpecificationError saying function names must be unique. Pass (name, function) tuples, such as [("lowest", lambda s: s.min()), ("highest", lambda s: s.max())], or use "min" and "max" as strings.