Sub topic 9
Grouping and aggregating
This chapter assumes you can write expressions with pl.col and use select, with_columns and filter. It uses the small employee DataFrame from the earlier chapters.
The working model
group_by is a context, like select. It splits the rows into groups that share the same key values. Then agg evaluates each expression once per group and reduces it to a single value. The result has one row per group. Its columns are the key columns, followed by one column per expression you passed to agg.
A basic aggregation
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
summary = (
df.group_by("dept")
.agg(
pl.col("salary").mean().alias("avg_salary"),
pl.len().alias("headcount"),
)
.sort("dept")
)
print(summary)The output has the columns dept, avg_salary and headcount. The eng row shows 110.0 and 2. The ops row shows 85.0 and 2. pl.len() counts the rows in each group.
Polars does not guarantee the order of groups. Call sort after agg when you need stable output. You can also pass maintain_order=True to group_by, which keeps groups in order of first appearance but is slower.
Richer expressions inside agg
Anything that produces one value per group works in agg. You can filter or sort inside the expression, so you don't need a separate pass over the data.
import polars as pl
df = pl.DataFrame(
{
"name": ["Ana", "Ben", "Cy", "Dee"],
"dept": ["eng", "eng", "ops", "ops"],
"salary": [120, 100, 80, 90],
}
)
stats = (
df.group_by("dept")
.agg(
pl.col("salary").min().alias("lowest"),
pl.col("salary").max().alias("highest"),
pl.col("name").sort_by("salary", descending=True).first().alias("top_earner"),
pl.col("salary").filter(pl.col("salary") >= 90).mean().alias("avg_90_plus"),
)
.sort("dept")
)
print(stats)Here top_earner is Ana for eng and Dee for ops. The filter inside agg applies only to that one expression, and the other columns still see every row of the group.
You can group by several keys, as in group_by("dept", "band"). You can also group by an expression, as in group_by((pl.col("salary") >= 100).alias("high_paid")).
Common errors
- Duplicate output names. Two expressions on
salarywithout.alias(...), such asmean()andmax(), both produce a column namedsalary. Polars raises a duplicate-column error. Give each aggregation an alias. - Expecting other columns to survive.
group_by("dept").agg(...)returns only the keys and the aggregates. A column likenamethat you don't aggregate is dropped. To keep per-row detail next to a group value, useover(), which is covered in the next chapter. - Relying on group order. Output order can change between runs. Sort explicitly.
- Returning a list by accident. An expression in
aggthat doesn't reduce, such aspl.col("salary")alone, gives a list column holding each group's values. This is sometimes useful, but often it means you forgot an aggregation like.sum().
Exercise
Using the DataFrame above, write a query that returns one row per dept with the column totalsalary (the sum of salary) and the column namesindept (the number of rows in the group), sorted by totalsalary descending. Why does the query need an explicit sort?
Show answer
df.groupby("dept").agg(pl.col("salary").sum().alias("totalsalary"), pl.len().alias("namesindept")).sort("totalsalary", descending=True). It needs the sort because groupby does not guarantee the order of the groups, so the rows could come back in a different order on each run. Without an alias, both expressions would not collide here, but totalsalary and namesin_dept are named explicitly for clarity.