Sub topic 9
Group by and aggregation
This chapter shows how to translate groupby code from pandas into Polars group_by. It assumes you can write pandas groupby().agg() with named aggregation, and that you have read the earlier chapters on expressions and on creating columns. The examples use Polars 1.x. Older releases spell group_by as groupby and pl.len() as pl.count().
The model: keys in, expressions out
A pandas groupby returns an object, and you then pick columns and functions with strings or tuples. A Polars group_by takes key columns, and agg takes a list of expressions. Each expression is reduced to one value per group.
The result has one row per group. The key columns come first, followed by one column per expression. There is no index, so as_index=False and reset_index() have no Polars equivalent.
A shared example
The examples below use this small frame. One price is missing, which matters for the null behavior later.
import polars as pl
df = pl.DataFrame(
{
"region": ["east", "east", "west", "west", "west"],
"channel": ["web", "store", "web", "web", "store"],
"price": [10.0, 20.0, 5.0, None, 8.0],
"qty": [3, 1, 10, 2, 5],
}
).with_columns((pl.col("price") * pl.col("qty")).alias("total"))Translating named aggregation
The pandas named aggregation agg(revenue=("total", "sum"), orders=("total", "count")) becomes a list of aliased expressions. You can also pass keyword arguments, which name the output columns directly.
summary = (
df.group_by("region")
.agg(
pl.col("total").sum().alias("revenue"),
pl.len().alias("orders"),
)
.sort("revenue", descending=True)
)
# Equivalent, using keyword names
summary_kw = (
df.group_by("region")
.agg(revenue=pl.col("total").sum(), orders=pl.len())
.sort("revenue", descending=True)
)Sorting by a column uses sort("revenue", descending=True). It does not use ascending=False.
Row order is not guaranteed
Polars computes groups in parallel, so the order of result rows can differ between runs. pandas sorts group keys by default (sort=True), which many scripts rely on without noticing. When you port code, choose one of two fixes:
- Add
.sort("region")after the aggregation to get sorted keys, as pandas does. - Pass
maintain_order=Truetogroup_byto keep groups in order of first appearance. This is slower, so use it only when you need it.
by_region = df.group_by("region").agg(pl.col("total").sum()).sort("region")
first_seen = df.group_by("region", maintain_order=True).agg(pl.col("total").sum())Several keys and several columns
Pass multiple keys as separate arguments or as a list. To apply one function to many columns, select them with pl.col("a", "b") and rename the outputs with name.suffix. Without the rename, every output would keep its input column name, and the aggregation would fail on duplicate names if you applied two functions.
by_pair = (
df.group_by("region", "channel")
.agg(
pl.col("price", "qty").mean().name.suffix("_mean"),
pl.col("total").max().alias("best_order"),
)
.sort("region", "channel")
)Count, size and null handling
The pandas count methods map as follows.
| pandas | Polars | Counts nulls? |
|---|---|---|
| `size()` | `pl.len()` | Yes, every row |
| `count()` | `pl.col("x").count()` | No, non-null values only |
| `nunique()` | `pl.col("x").n_unique()` | Counts null as one value |
| `first()` | `pl.col("x").first()` | Returns the first value, even if null |
pandas first() skips missing values. Polars first() does not. If you need the first non-null value, use pl.col("x").drop_nulls().first().
checks = df.group_by("region").agg(
pl.len().alias("rows"),
pl.col("total").count().alias("non_null_totals"),
pl.col("total").null_count().alias("null_totals"),
pl.col("total").drop_nulls().first().alias("first_total"),
).sort("region")In the example, the west group has three rows and two non-null totals.
Null and NaN also behave differently inside aggregations. Polars sum and mean skip nulls, but a NaN in a float column propagates into the result. pandas skips both. If your data uses NaN as a missing marker, convert it first with fill_nan(None) or pl.col("x").fill_nan(None).
Conditional aggregation
pandas often needs a filtered frame or a lambda to aggregate a subset of each group. In Polars you call filter on the expression inside agg, so the filter applies per group.
conditional = df.group_by("region").agg(
pl.col("total").sum().alias("revenue"),
pl.col("total").filter(pl.col("channel") == "web").sum().alias("web_revenue"),
(pl.col("channel") == "web").mean().alias("web_share"),
).sort("region")The last expression works because a boolean column averages to the fraction of true values.
Replacing groupby apply
Most groupby().apply(func) code can become expressions. Two common cases:
- Top rows per group. Sort once, then take the head of each group.
- Lists of values. An expression that returns a column without reducing it gives a list per group.
top_two = (
df.sort("total", descending=True, nulls_last=True)
.group_by("region", maintain_order=True)
.head(2)
)
totals_as_lists = df.group_by("region").agg(pl.col("total")).sort("region")In the second query, the total column of the result has dtype List(Float64). Use explode("total") to turn it back into one row per value.
As a last resort, group_by(...).map_groups(func) runs a Python function on each group's DataFrame. It is slow and cannot be optimized, so use it only when no expression fits.
Grouping by time
For pd.Grouper(key="ts", freq="1d") or resample, use group_by_dynamic. The column must be sorted.
from datetime import datetime
events = pl.DataFrame(
{
"ts": [datetime(2026, 1, 1, 9), datetime(2026, 1, 1, 15), datetime(2026, 1, 2, 8)],
"amount": [5.0, 7.0, 3.0],
}
).sort("ts")
daily = events.group_by_dynamic("ts", every="1d").agg(pl.col("amount").sum())Common errors
AttributeError: 'DataFrame' object has no attribute 'groupby'. Usegroup_by.- Using a string where pandas used a tuple.
agg(("total", "sum"))is not valid. Writepl.col("total").sum(). - Duplicate output names. Two expressions on the same column without
aliasproduce aDuplicateError. Alias each one. - Expecting an index. Key columns are ordinary columns. Selecting
regionafter the aggregation works directly. - Assuming sorted output. Add
sortormaintain_order=Truewhen order matters, especially in tests.
Exercise
In pandas, df.groupby("region")["total"].count() returns 2 for a group with three rows where one total is missing. You port it to df.group_by("region").agg(pl.len()) and get 3. What is the correct Polars expression to match the pandas result, and which expression gives the pandas size() result?
Show answer
Use pl.col("total").count(), which counts only non-null values and matches the pandas count(). pl.len() counts every row in the group, so it matches pandas size().
Exercise
A ported report groups by "region" and prints the rows in a different order on each run. Name two ways to make the order stable and say which one costs more.
Show answer
Add .sort("region") after the aggregation to get sorted keys like pandas, or pass maintainorder=True to groupby to keep first-appearance order. The maintain_order option is the more expensive one, because it limits parallel work during grouping.