Sub topic 3
Multiple and conditional aggregations
This chapter assumes you can build a DataFrame, select columns with pl.col, and run a basic group_by(...).agg(...). It extends that pattern in two ways. You can compute several summaries in one pass, and you can restrict each summary to the rows you care about.
Several aggregations in one agg
agg accepts any number of expressions. Each expression produces one output column, and Polars computes them all in the same grouping pass. You don't need a separate group_by for each summary.
Every output column needs a unique name. Two expressions on sales would both be named sales, so use alias to rename them. Without it, Polars raises a duplicate-column error.
Filtering inside an aggregation
Calling filter on an expression inside agg limits that one aggregation to the matching rows. The other expressions in the same agg still see the whole group.
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"product": ["a", "b", "a", "b", "b"],
"sales": [10, 20, 5, 15, 25],
})
out = df.group_by("region").agg(
pl.col("sales").filter(pl.col("product") == "b").sum().alias("b_sales"),
pl.col("sales").mean().alias("avg_sales"),
).sort("region")
print(out)The result has one row per region:
| region | b_sales | avg_sales |
|---|---|---|
| east | 20 | 15.0 |
| west | 40 | 15.0 |
b_sales counts only product b rows. avg_sales averages every row in the group. Both are computed in the same group_by.
Counting matching rows
pl.len() counts every row in the group and ignores filters. To count rows that match a condition, sum a boolean expression. True counts as 1 and False as 0.
out = df.group_by("region").agg(
pl.len().alias("rows"),
(pl.col("product") == "b").sum().alias("b_rows"),
).sort("region")
print(out)East has 2 rows and 1 b row. West has 3 rows and 2 b rows.
Common errors
- Duplicate output names. Two expressions that both produce
salesfail. Addaliasto each. - Forgetting that a filter can match nothing. If a group has no matching rows,
sumreturns 0 butmeanreturns null. Check for nulls before using the result in later arithmetic. - Filtering the whole DataFrame first. Calling
df.filter(...)beforegroup_bydrops groups with no matches from the output. A filter insideaggkeeps every group. - Assuming row order. Group order is not guaranteed, so add
sortwhen you need stable output. The next chapter covers this.
Exercise
Using the df above, write a groupby on "region" that returns, for each region, the sum of sales for product "a" named asales, and the number of rows named rows. What are the values for west?
Show answer
df.groupby("region").agg(pl.col("sales").filter(pl.col("product") == "a").sum().alias("asales"), pl.len().alias("rows")).sort("region"). For west, a_sales is 5 and rows is 3.