Sub topic 12
Naming aggregated columns
This chapter assumes you can build a DataFrame, select columns, and call groupby with a single aggregation such as df.groupby("region")["units"].sum(). Here you will use named aggregation to control the output column names.
Why names matter
A plain groupby(...).sum() gives you columns with the same names as the inputs. That is unclear once you mix different statistics, such as a sum of units and a mean of price. Named aggregation lets you choose each result column's name and say which column and function produce it.
The syntax
Pass keyword arguments to agg. The keyword is the new column name. The value is a tuple of (input column, function).
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],
})
summary = df.groupby("region").agg(
total_units=("units", "sum"),
avg_price=("price", "mean"),
orders=("product", "size"),
)
print(summary)The output has one row per region and one column per keyword:
total_units avg_price orders
region
East 15.0 3.25 2
North 10.0 3.25 2
South 17.0 3.25 2total_units is a float because units contains a missing value, which forces a float column.
Choosing the function
The function can be a string such as "sum", "mean", "min", "max", "count" or "size". It can also be any callable, including a lambda.
detail = df.groupby("region").agg(
orders=("product", "size"),
orders_with_units=("units", "count"),
units_range=("units", lambda s: s.max() - s.min()),
)
print(detail)size counts every row in the group. count counts only non-missing values. North has two rows but one known units value, so orders is 2 and orders_with_units is 1.
Common errors
- Passing a bare string instead of a tuple.
total=("units")is not a tuple, because the parentheses alone do nothing. Write("units", "sum"). - Using a name that is not a valid Python keyword. Keywords like
total unitsfail. Use underscores, or unpack a dictionary:agg(**{"total units": ("units", "sum")}). - Expecting
regionas a column. The group keys become the index. Addas_index=Falsetogroupby, or call.reset_index(), to turn them into a normal column. - Using the older dictionary form.
agg({"units": ["sum", "mean"]})returns two-level column labels (a MultiIndex), which are harder to work with. Named aggregation returns flat names.
Using the result
Because the output columns have meaningful names, you can sort and select them directly, which the next chapter does:
print(summary.sort_values("total_units", ascending=False))Exercise
Using the df above, write a groupby on product that returns a table with columns n_rows (number of rows), known_units (number of non-missing units) and max_units (largest units). Which product has known_units smaller than n_rows?
Show answer
Use df.groupby("product").agg(n_rows=("units", "size"), known_units=("units", "count"), max_units=("units", "max")). Product B has 3 rows but only 2 known units values, because one B row (North) has a missing value. So known_units is 2 and n_rows is 3 for B. Product A has 3 rows and 3 known values.