Sub topic 9
Group by and aggregation
This chapter assumes you know pandas groupby, including named aggregation, and that you have read the earlier chapters on expressions and with_columns.
The shape of a Polars group-by
In Polars, group_by takes the key columns and agg takes expressions. Each expression produces one output column. The result is a plain DataFrame with the keys as ordinary columns, so there is no index and no as_index=False or reset_index().
import polars as pl
df = pl.DataFrame(
{
"region": ["west", "east", "west", "east", "north"],
"price": [10.0, 20.0, 30.0, 40.0, 50.0],
"qty": [1, 5, 4, 3, 2],
}
)
summary = (
df.with_columns((pl.col("price") * pl.col("qty")).alias("total"))
.group_by("region")
.agg(
pl.col("total").sum().alias("revenue"),
pl.len().alias("orders"),
)
.sort("revenue", descending=True)
)
print(summary)The alias call plays the role of the keyword name in pandas named aggregation. Without it, the output column keeps the input name. Two aggregations of the same column therefore need aliases, or Polars raises a duplicate-name error.
Common translations
| pandas | Polars |
|---|---|
| `groupby("k", as_index=False)` | `group_by("k")` |
| `agg(x=("col", "sum"))` | `agg(pl.col("col").sum().alias("x"))` |
| `size()` | `pl.len()` |
| `count()` (non-missing values) | `pl.col("col").count()` |
| `nunique()` | `pl.col("col").n_unique()` |
| `sort_values("x")` | `sort("x")` |
For several keys, pass a list: group_by(["region", "year"]). To apply one aggregation to many columns, use a selector expression such as pl.col("price", "qty").mean(). Polars keeps each input column name for the results.
Differences that change results
- Null keys: pandas drops rows whose key is missing (
dropna=True). Polars keeps null as its own group. - Counting:
pl.len()counts all rows in the group.pl.col("x").count()counts only non-null values. pandassize()andcount()follow the same split. - NaN versus null:
sumandmeanskip nulls, but they do not skip NaN. A single NaN in a float column makes that group's sum NaN. Convert withfill_nan(None)first if you want pandas-like skipping. - Expressions inside agg: you can compute inside
agg, as in(pl.col("price") * pl.col("qty")).sum(). This avoids creating a temporary column.
Exercise
A pandas report was produced with groupby("region") and lists regions alphabetically. After porting to Polars, the rows come out in a different order on each run. What is the fix, and why does maintain_order=True not fix it?
Show answer
Add .sort("region") after agg. Polars does not sort group keys, so the order is arbitrary. maintain_order=True only makes the order stable, following the first appearance of each key in the input. That order is repeatable but not alphabetical.