Sub topic 12
Naming aggregated columns
This chapter covers named aggregation in groupby(...).agg(...). It assumes you can build a DataFrame, select columns, and run a basic groupby with one aggregation such as df.groupby("region")["units"].sum(). It uses the sales table from earlier chapters, so the setup is repeated here.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})Why names matter
Suppose you want several statistics per group. The older approach passes a list or dictionary of function names to agg, and pandas builds the column labels itself:
print(df.groupby("region")["units"].agg(["sum", "mean", "max"]))The result has columns sum, mean and max. Those labels are fine for one column. When you summarise several columns, they become ambiguous, and a lambda shows up as a column literally called <lambda>. You then have to rename everything afterwards.
Named aggregation fixes this. You choose the output name, the input column and the function in one place.
The keyword syntax
Each keyword argument to agg defines one output column. The keyword is the new column name, and the value is a two-item tuple of (input column, function).
summary = df.groupby("region").agg(
total_units=("units", "sum"),
avg_price=("price", "mean"),
orders=("product", "size"),
)
print(summary) total_units avg_price orders
region
East 15.0 3.25 2
North 10.0 3.25 2
South 17.0 3.25 2The groups become the index, and the columns appear in the order you wrote the keywords. total_units is a float because the units column holds NaN, which forces float storage.
What can go in the tuple
The first item must be an existing column name. The second item can take several forms:
| Form | Example | Notes |
|---|---|---|
| Method name as a string | `("units", "sum")` | Uses pandas' optimised implementation. Preferred when one exists. |
| Other string names | `("price", "nunique")` | Works for any `groupby` method that returns one value per group. |
| NumPy or built-in function | `("units", max)` | Works, but pandas may warn and suggest the string form. |
| Lambda or named function | `("units", lambda s: s.max() - s.min())` | Receives the group's values as a Series and must return one scalar. |
A custom function is useful for statistics that have no built-in name. This example adds a range and compares count with size:
summary = df.groupby("region").agg(
total_units=("units", "sum"),
units_reported=("units", "count"),
orders=("product", "size"),
best_order=("units", "max"),
unit_range=("units", lambda s: s.max() - s.min()),
)
print(summary) total_units units_reported orders best_order unit_range
region
East 15.0 2 2 8.0 1.0
North 10.0 1 2 10.0 0.0
South 17.0 2 2 12.0 7.0North has two orders but only one reported unit count. count ignores NaN and size counts every row, so units_reported and orders differ for that region. The lambda also skips NaN, because Series.max and Series.min skip it by default.
You can aggregate the same input column several times, as long as each output name is different:
spread = df.groupby("region").agg(
units_min=("units", "min"),
units_max=("units", "max"),
)
print(spread)Using pd.NamedAgg
pd.NamedAgg is a named tuple with the fields column and aggfunc. It does the same job as a plain tuple, but the fields are labelled, which can read better in long calls:
summary = df.groupby("region").agg(
total_units=pd.NamedAgg(column="units", aggfunc="sum"),
avg_price=pd.NamedAgg(column="price", aggfunc="mean"),
)
print(summary)Plain tuples and NamedAgg objects can be mixed in one call.
Names that are not valid Python identifiers
A keyword argument must be a valid Python name, so total units with a space cannot be written directly. Build a dictionary and unpack it with **:
summary = df.groupby("region").agg(**{
"total units": ("units", "sum"),
"avg price ($)": ("price", "mean"),
})
print(summary.columns.tolist())This prints ['total units', 'avg price ($)']. The same technique works when the output names are generated by code, for example from a loop over column names. For later steps in a method chain, plain snakecase names are easier to use, because they allow `summary.totalunits and query` expressions.
Keeping the group column as a column
By default the group keys become the index. Pass as_index=False to keep them as an ordinary column and get a fresh integer index:
flat = df.groupby("region", as_index=False).agg(
total_units=("units", "sum"),
orders=("product", "size"),
)
print(flat) region total_units orders
0 East 15.0 2
1 North 10.0 2
2 South 17.0 2You get the same table by calling .reset_index() on the default result. Use as_index=False when the next step is a merge, a plot call that expects a column, or a CSV export.
Aggregating a single column
When you select one column before agg, the keyword values are just functions, because the column is already chosen:
by_region = df.groupby("region")["units"].agg(
total="sum",
biggest="max",
)
print(by_region)The result is still a DataFrame with columns total and biggest. If you write a tuple here, pandas raises an error, because the column is already fixed by the selection.
Common errors
- Tuple in the wrong order.
total=("sum", "units")looks for a column namedsumand raises aKeyErrorsaying the column does not exist. The column always comes first. - A function that returns more than one value. A lambda such as
lambda s: s.nlargest(2)returns a Series for each group. Named aggregation requires one scalar per group, so pandas raises an error. Usetransform,applyornlargestper group for that task. - Reusing an output name. Python rejects
a=(...), a=(...)as a syntax error before pandas sees it. With the**{...}form, a repeated key in a dictionary literal silently keeps only the last entry. - Old nested renaming. The form
agg({"units": {"total": "sum"}})was removed. Current pandas raises aSpecificationErrorsaying nested renamers are not supported. Use named aggregation instead. - Positional arguments mixed with keywords. Calling
agg("sum", total=("units", "sum"))does not combine the two styles. Use either one function spec or keyword-based named aggregation in a given call.
Preparing the result for sorting
The named columns make the next step easy to read, since you can refer to them by meaningful names. Sorting the summary by total_units is covered in the next chapter, and the result is a regular DataFrame, so everything from the sorting chapters applies to it.
Exercise
Write a groupby on product that returns, for each product, a column total_units (sum of units), a column avg_price (mean of price) and a column rows_missing_units (the number of rows whose units value is missing). Which aggregation functions do you use for the third column, and why?
Show answer
Use a lambda for the third column: df.groupby("product").agg(total_units=("units", "sum"), avg_price=("price", "mean"), rows_missing_units=("units", lambda s: s.isna().sum())). The built-in size counts all rows and count counts only non-missing values, so neither gives the number of missing values directly. Another valid answer is to compute size and count separately and subtract afterwards. For product A the result is totalunits 30.0, avgprice 2.5 and 0 missing. For product B it is 12.0, 4.0 and 1 missing.
Exercise
This call fails: df.groupby("region").agg(total=("sum", "units")). What is the error, and how do you fix it? Then rewrite the fixed call so that the group key stays a regular column.
Show answer
The tuple order is reversed. The column name must come first, so pandas looks for a column called sum and raises a KeyError. The fix is df.groupby("region").agg(total=("units", "sum")). To keep the region as a column, add as_index=False: df.groupby("region", as_index=False).agg(total=("units", "sum")).