In pandas, how do you compute several differently named summary columns per customer with `groupby().agg`, and why prefer named aggregation?
answer
- keywords name the outputs
- a pair: source column and function
- lists stack two levels of labels
- NamedAgg is only a namedtuple
basics
~20 sPass keywords to agg, each naming an output column and pairing a source column with a function: agg(total=('amount', 'sum'), orders=('amount', 'size')). Lists and dicts of functions produce two-level column labels to flatten; named aggregation gives flat, chosen names.
solid answer
~40 sNamed aggregation is `DataFrameGroupBy.agg` called with keyword arguments: each keyword is an output column name and each value is a `(column, aggfunc)` tuple or the equivalent `pd.NamedAgg(column=..., aggfunc=...)`. So `orders.groupby('customer_id').agg(total=('amount', 'sum'), avg=('amount', 'mean'), categories=('category', 'nunique'))` returns one row per customer with exactly those three columns, in that order. A list, `[['amount']].agg(['sum', 'mean'])`, labels the result with a two-level column `MultiIndex` of (column, function), and a dict, `agg({'amount': ['sum', 'mean']})`, picks functions per column but stacks labels the same way whenever a value is a list. Those labels then need renaming or flattening, which is where pipelines break. A name that is not a valid identifier goes in through `**{'total spend': ('amount', 'sum')}`.
code
python · 18 linesimport pandas as pd
orders = pd.DataFrame({
"customer_id": ["c1", "c2", "c1", "c1", "c2"],
"category": ["books", "toys", "books", "garden", "toys"],
"amount": [20.0, 35.0, 5.0, 50.0, 15.0],
})
gb = orders.groupby("customer_id")
stacked = gb[["amount"]].agg(["sum", "mean"])
print(stacked.columns.tolist())
summary = gb.agg(
total=("amount", "sum"),
biggest=pd.NamedAgg(column="amount", aggfunc="max"),
categories=("category", "nunique"),
)
print(summary)go deeper
Recall the named aggregation form, output=('column', 'function'), and that it gives one flat column per keyword.
Explain how list, dict and named forms differ in labels, why a list on several columns returns a two-level column MultiIndex, and that NamedAgg is only a namedtuple.
Show that you keep aggregation outputs stable for downstream code: named columns, no mangled lambda names, no fragile flatten-and-rename steps, and the right fix for SpecificationError.
Weigh standardising named aggregation in shared transforms so feature and report columns are declared once, reviewed easily and never renamed in a separate step.
## Three ways to call `agg` `DataFrameGroupBy.agg` (also spelled `aggregate`) accepts several shapes of argument, and the shape decides the column labels you get back: | Call | What it computes | Column labels of the result | |---|---|---| | `gb[['amount']].agg(['sum', 'mean'])` | every listed function on every selected column | two-level `MultiIndex`: `('amount', 'sum')`, `('amount', 'mean')` | | `gb.agg({'amount': 'sum', 'category': 'nunique'})` | one function per named column | flat: `amount`, `category` | | `gb.agg({'amount': ['sum', 'mean']})` | a list of functions for a column | two-level `MultiIndex` again | | `gb.agg(total=('amount', 'sum'))` | named aggregation | flat: exactly the keyword names | Here `gb` is `orders.groupby('customer_id')`. On a single selected column, a `SeriesGroupBy`, a list gives flat labels named after the functions (`sum`, `mean`), because there is only one source column to label. ## How named aggregation works - **The keyword is the output name.** In `agg(total=('amount', 'sum'))`, `total` is the column you get back, not a column you read from. - **The value is a pair**: the source column, then the aggregation. The aggregation can be a **string alias** such as `'sum'`, `'mean'`, `'size'` or `'nunique'`, or a callable. - **`pd.NamedAgg` is just a `namedtuple`** with the fields `column` and `aggfunc`. `pd.NamedAgg(column='amount', aggfunc='sum')` and `('amount', 'sum')` behave identically; the namedtuple only makes the call read more clearly. - **Order and names are under your control**: the result's columns appear in the order of the keywords, so a report's layout is fixed in one place. - **The same source column can feed several outputs**, such as a total and a maximum from `amount`. - **Non-identifier names** such as `'total spend'` go in by unpacking a dict: `agg(**{'total spend': ('amount', 'sum')})`. - **On a `SeriesGroupBy`** there is no column to select, so the values are just functions: `orders.groupby('customer_id')['amount'].agg(total='sum', biggest='max')`. - **Extra arguments are not forwarded.** Only `(column, aggfunc)` pairs are accepted as keywords; when a function needs a parameter, bind it first with `functools.partial` or wrap it in a lambda. `as_index=False` combines with all of this: the keys arrive as ordinary columns ahead of the named outputs. ## What lists and dicts leave behind The list and dict forms are fine for exploration, but they leave work downstream: 1. **Stacked labels.** A two-level column `MultiIndex` makes `result['amount']['sum']` the way in, and most exports and merges want flat names. The usual fix is `result.columns = ['_'.join(c) for c in result.columns]`, which yields `amount_sum` and `amount_mean`, a convention someone must then remember. 2. **Mangled lambda names.** Several lambdas in a list come back as `<lambda_0>`, `<lambda_1>`, and so on, which says nothing about what they computed. 3. **Renames drift.** A separate `rename(columns=...)` step after the aggregation has to be kept in sync with the list by hand. Named aggregation removes all three: each output's name, source and function sit together in one keyword. ## Errors you will meet - A dict that names a column the frame lacks raises a **`KeyError`**. - A dict passed to a **`SeriesGroupBy`**, as in `gb['amount'].agg({'total': 'sum'})`, raises **`SpecificationError`** with the message "nested renamer is not supported"; use keywords instead. - Mixing a positional function with named keywords, as in `agg('sum', total=('amount', 'sum'))`, raises a **`TypeError`**, because the keywords are passed on to the aliased method. ## First and last values per group Two aliases come up in every customer summary, and they are easy to misread: - **`'first'` and `'last'`** return the first and last **non-missing** value of each column within the group, because `first()` and `last()` have `skipna=True` by default. A customer whose first order had no coupon code still gets a coupon value from a later order. - They follow the **row order of the frame**, not a date. Sort first, `orders.sort_values('order_date').groupby('customer_id').agg(first_order=('order_date', 'first'), last_order=('order_date', 'last'))`, or use `'min'` and `'max'` on the date column, which do not depend on order at all. - **`nth(0)`** is not a synonym: it returns the actual first row of each group, missing values included, and keeps the original row labels instead of indexing the result by key. ## Choosing a form - **Named aggregation** for anything that leaves the notebook: reports, features, tables other code reads. - **A list** for a quick look at several statistics of one column. - **A dict of single functions** when the output names should simply repeat the input names.
- How do you name an output column `total spend`, with a space?A keyword argument cannot contain a space, so build a dict and unpack it: `orders.groupby('customer_id').agg(**{'total spend': ('amount', 'sum')})`. pandas reads the unpacked dict as named aggregation, and the key becomes the output column name.
- An aggregation needs a parameter, such as the 90th percentile; how do you pass it in named aggregation?Named aggregation does not forward extra keyword arguments to the functions; only `(column, aggfunc)` pairs are accepted. Bind the parameter first, with `functools.partial` or a lambda such as `p90=('amount', lambda s: s.quantile(0.9))`. The lambda runs per group in Python, so prefer a string alias whenever one exists.
- What happens if you pass a dict to `orders.groupby('customer_id')['amount'].agg`?It raises `SpecificationError: nested renamer is not supported`. A dict-to-rename form on a single column was removed long ago; on a `SeriesGroupBy`, name the outputs with keywords instead, as in `.agg(total='sum', biggest='max')`.
- agg(['sum', 'mean']) on several columns returns flat columns named sum and mean.
- In agg(total=('amount', 'sum')) the keyword total names the input column.
- pd.NamedAgg runs faster than a plain (column, aggfunc) tuple.
- Named aggregation passes extra keyword arguments through to each function.
- A dict of output names works on a single selected column.