Sub topic 3
Multiple and conditional aggregations
This chapter assumes you can write a basic group_by(...).agg(...) call and know that pl.col("x").sum() is an expression. Here you will put several summaries in one agg, restrict individual summaries to some rows, and avoid the naming and empty-group problems that come with both.
Several aggregations in one pass
agg accepts any number of expressions. Each expression produces one column in the result, and Polars evaluates them together over the same groups. You do not need one group_by per statistic.
The examples in this chapter use the same small table.
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").sum().alias("total"),
pl.col("sales").mean().alias("avg"),
pl.col("sales").max().alias("best"),
pl.len().alias("rows"),
).sort("region")
print(out)
# east: total 30, avg 15.0, best 20, rows 2
# west: total 45, avg 15.0, best 25, rows 3The sort call is there because group order is not guaranteed. A later chapter covers maintain_order.
Naming output columns
An aggregation keeps the name of the column it came from. Two aggregations of sales therefore produce two columns both named sales, and Polars raises a DuplicateError. There are three ways to avoid this:
.alias("total")names one expression.- Keyword arguments name an expression by the keyword, as in
agg(total=pl.col("sales").sum()). .name.suffix("_x")or.name.prefix("x_")renames every output of an expression that covers several columns.
df2 = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"sales": [10, 20, 5, 15, 25],
"qty": [1, 2, 3, 4, 5],
})
out = df2.group_by("region").agg(
pl.col("sales", "qty").sum().name.suffix("_total"),
biggest_sale=pl.col("sales").max(),
).sort("region")
print(out)
# columns: region, sales_total, qty_total, biggest_sale
# east: 30, 3, 20
# west: 45, 12, 25pl.col("sales", "qty") selects both columns. The sum() is applied to each, and name.suffix renames each result.
Counting rows
Two counting expressions behave differently when nulls are present:
| Expression | Counts |
|---|---|
| `pl.len()` | Every row in the group, including nulls |
| `pl.col("x").len()` | Every row of that column, including nulls |
| `pl.col("x").count()` | Only the non-null values of that column |
Use pl.len() for "how many rows". Use count() for "how many rows have a value".
Aggregations that return lists
An expression in agg that does not reduce to a single value yields a list per group. This is useful for inspecting group contents.
out = df.group_by("region").agg(
pl.col("product"),
pl.col("sales").sort(descending=True).alias("sales_desc"),
).sort("region")
print(out)
# east: product ["a", "b"], sales_desc [20, 10]
# west: product ["a", "b", "b"], sales_desc [25, 15, 5]If you meant to get a scalar and see a list[...] column, you probably forgot the reducing step such as sum() or first().
Conditional aggregations
Calling filter on an expression inside agg restricts only that expression to the rows where the predicate is true. Other expressions in the same agg still see the whole group.
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)
# east: b_sales 20, avg_sales 15.0
# west: b_sales 40, avg_sales 15.0The predicate is evaluated inside each group, so pl.col("product") refers to the product values of that group's rows.
Combining filtered aggregations
Because every expression filters independently, you can build several differently filtered summaries in a single group_by. You can also combine them arithmetically, since the result of a reduction is a scalar within each group.
out = df.group_by("region").agg(
pl.col("sales").filter(pl.col("product") == "a").sum().alias("a_sales"),
pl.col("sales").filter(pl.col("product") == "b").sum().alias("b_sales"),
(
pl.col("sales").filter(pl.col("product") == "b").sum()
/ pl.col("sales").sum()
).alias("b_share"),
).sort("region")
print(out)
# east: a_sales 10, b_sales 20, b_share 0.667
# west: a_sales 5, b_sales 40, b_share 0.889To combine conditions, join them with & or | and put each comparison in parentheses, for example filter((pl.col("product") == "b") & (pl.col("sales") > 10)). Python's operator precedence makes the parentheses necessary.
Counting rows that match a condition
There are two ways to count matches. You can filter and then take len(), or you can sum a boolean expression, because True counts as 1.
out = df.group_by("region").agg(
pl.col("sales").filter(pl.col("sales") >= 15).len().alias("big_a"),
(pl.col("sales") >= 15).sum().alias("big_b"),
).sort("region")
print(out)
# east: big_a 1, big_b 1
# west: big_a 2, big_b 2Both give the same answer here. The boolean sum is shorter when you only need a count. The filter form is more general because you can follow it with any reduction.
What happens when no rows match
A group can exist while the filter leaves it with zero rows. The reduction then runs on an empty column, and the result depends on the function.
out = df.group_by("region").agg(
pl.col("sales").filter(pl.col("product") == "c").sum().alias("c_sum"),
pl.col("sales").filter(pl.col("product") == "c").mean().alias("c_mean"),
pl.col("sales").filter(pl.col("product") == "c").len().alias("c_rows"),
).sort("region")
print(out)
# both regions: c_sum 0, c_mean null, c_rows 0sum and len return 0. mean, max, min, and first return null. Keep this in mind when you divide one conditional aggregate by another, because a null or zero denominator gives a null or an infinite share.
Filter inside agg versus filter before group_by
Filtering the whole DataFrame first looks similar, but it behaves differently.
only_b = df.filter(pl.col("product") == "b").group_by("region").agg(
pl.col("sales").sum().alias("b_sales")
).sort("region")
print(only_b)
# east: 20, west: 40Here every aggregate in the agg sees only product b, and a region with no b rows would disappear from the result. With filter inside agg, every region stays in the output and each expression chooses its own rows.
| Approach | Rows seen by each aggregate | Groups with no matches |
|---|---|---|
| `filter` inside `agg` | Chosen per expression | Kept, with 0 or null values |
| `df.filter(...)` before `group_by` | The same filtered rows for all | Dropped from the result |
| `pl.when(...).then(...)` inside `agg` | All rows, with non-matching values replaced | Kept |
The when/then form is useful when you want to replace values rather than drop rows. For example, pl.when(cond).then(pl.col("sales")).otherwise(0).sum() matches the filtered sum. Without otherwise, the non-matching values become null, and most reductions skip nulls.
Exercise
Using the DataFrame df from this chapter, write a groupby on "region" that returns, for each region, the number of rows with sales >= 15 (named "bigrows") and the mean sales of only those rows (named "big_avg"). What does the result contain for each region?
Show answer
df.groupby("region").agg(pl.col("sales").filter(pl.col("sales") >= 15).len().alias("bigrows"), pl.col("sales").filter(pl.col("sales") >= 15).mean().alias("bigavg")).sort("region"). East has one qualifying row (20), so bigrows is 1 and bigavg is 20.0. West has two (15 and 25), so bigrows is 2 and big_avg is 20.0.
Exercise
A colleague wrote df.group_by("region").agg(pl.col("sales").sum(), pl.col("sales").max()) and gets an error. Why, and how do you fix it?
Show answer
Both expressions produce a column named "sales", so Polars reports a duplicate name. Give each an alias, for example pl.col("sales").sum().alias("total") and pl.col("sales").max().alias("best"), or use keyword names such as total=... and best=....