Sub topic 6
Several aggregations at once with agg and named aggregation
This chapter assumes you can create a DataFrame, select columns, and run a single aggregation such as groupby("region")["revenue"].sum(). Here you will compute several summaries in one call and control the names of the output columns.
Why use agg
Calling sum(), then mean(), then nunique() means three passes over the groups and three results to join. The agg method (short for aggregate) computes several summaries in one call and returns one table.
All 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],
})A list of functions on one column
Pass a list of function names to agg after selecting a column. You get one output column per function.
print(df.groupby("region")["revenue"].agg(["sum", "mean", "max"]))
# sum mean max
# region
# North 175.0 87.500000 100.0
# South 220.0 73.333333 120.0The function names are strings that pandas looks up. You can also pass Python callables such as max or numpy.mean, but strings are the clearest choice and the fastest.
Named aggregation
When different columns need different summaries, use named aggregation. Each keyword argument sets the name of an output column. Its 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 2The result has flat column names that you chose, so no later renaming is needed. The keyword names become the column labels, so they must be valid Python identifiers. If you need a name with spaces, unpack a dictionary: agg(**{"total units": ("units", "sum")}).
Other ways to pass a mapping
You can also give agg a dictionary that maps column names to a function or a list of functions.
print(df.groupby("region").agg({"units": "sum", "revenue": ["min", "max"]}))
# units revenue
# sum min max
# region
# North 15 75.0 100.0
# South 18 30.0 120.0A list of functions inside a dictionary produces a two-level column index (a MultiIndex). That is awkward to select from, which is why named aggregation is usually better.
| Form | Output columns | Best for |
|---|---|---|
| `["sum", "mean"]` on one column | One per function | Quick look at one column |
| `{"col": "sum"}` | One per column | Simple per-column choices |
| `{"col": ["min", "max"]}` | Two-level MultiIndex | Rarely, when you need the hierarchy |
| `name=("col", "func")` | Flat, named by you | Most summary tables |
Common errors
- Passing a bare string as a pair:
total=("units")is not a tuple, because the parentheses alone do nothing. Write("units", "sum"). - Using the same keyword twice, which Python rejects as a syntax error. Choose a distinct name for each output.
- Aggregating a text column with a numeric function such as
"mean", which raises aTypeError. Choose functions that fit the column's type. - Using a function that returns more than one value per group.
aggneeds one value per group. Usetransformorapplyfor other shapes, covered in later chapters.
Exercise
Using the DataFrame above, write a named aggregation grouped by "product" that returns the total revenue as total_revenue and the number of distinct regions as n_regions.
Show answer
df.groupby("product").agg(totalrevenue=("revenue", "sum"), nregions=("region", "nunique")). Product A gives 200.0 and 2, and product B gives 195.0 and 2.