Sub topic 10
Replacing transform with over
This chapter assumes you know pandas groupby().transform(), can write basic Polars expressions (pl.col, with_columns, group_by().agg()), and understand that Polars frames are immutable. It covers how to compute a per-group value and attach it to every row, which is what transform does in pandas.
The problem `transform` solves
A group-by with agg collapses each group to one row. Often you want the opposite: keep every row and add a column that depends on the row's group. Typical cases are the group mean, the share of the group total, a rank inside the group, or a running total inside the group.
In pandas you use groupby(...).transform(...). In Polars you write the expression as usual and add .over(...) to it. The result has the same number of rows as the input.
import pandas as pd
import numpy as np
import polars as pl
data = {
"region": ["north", "north", "south", "south", "south"],
"total": [50.0, 150.0, 80.0, 120.0, 200.0],
}
# pandas
pdf = pd.DataFrame(data)
pdf["region_mean"] = pdf.groupby("region")["total"].transform("mean")
pdf["size"] = np.where(pdf["total"] > 100, "large", "small")
# Polars
df = pl.DataFrame(data)
df = df.with_columns(
pl.col("total").mean().over("region").alias("region_mean"),
pl.when(pl.col("total") > 100)
.then(pl.lit("large"))
.otherwise(pl.lit("small"))
.alias("size"),
)
print(df)The over call turns pl.col("total").mean() from a whole-column aggregation into a per-group aggregation whose result is broadcast back to each row of the group. The when/then/otherwise chain replaces np.where and conditional assignment. It is an expression too, so it can sit in the same with_columns call.
How `over` works
Without over, pl.col("total").mean() inside with_columns returns one value, and Polars broadcasts it to every row. With over("region"), Polars computes one value per region and maps each value back to the rows of that region.
df.select(
pl.col("total").mean().alias("global_mean"),
pl.col("total").mean().over("region").alias("region_mean"),
)The output keeps the input's row order. Unlike pandas, there is no index to align on, so rows are matched by position. The mapping is done internally by Polars and you never have to merge the aggregate back yourself.
Mapping common `transform` patterns
| pandas | Polars |
|---|---|
| `g["x"].transform("mean")` | `pl.col("x").mean().over("g")` |
| `g["x"].transform("sum")` | `pl.col("x").sum().over("g")` |
| `g["x"].transform("count")` | `pl.col("x").count().over("g")` |
| `g["x"].transform("size")` | `pl.len().over("g")` |
| `g["x"].cumsum()` | `pl.col("x").cum_sum().over("g")` |
| `g["x"].rank()` | `pl.col("x").rank().over("g")` |
| `g["x"].shift(1)` | `pl.col("x").shift(1).over("g")` |
| `x / g["x"].transform("sum")` | `pl.col("x") / pl.col("x").sum().over("g")` |
Note two differences. transform("count") in pandas counts non-null values, and Polars count() does the same. To count rows including nulls, use pl.len(). Also, the Polars method names for cumulative operations carry an underscore: cum_sum, cum_max, cum_prod.
Arithmetic with group values
Because over is part of an expression, you can combine it with other operations in one step. In pandas this normally takes a temporary column or a lambda.
df = pl.DataFrame(
{
"region": ["north", "north", "south", "south", "south"],
"total": [50.0, 150.0, 80.0, 120.0, 200.0],
}
)
result = df.with_columns(
(pl.col("total") / pl.col("total").sum().over("region")).alias("share"),
(pl.col("total") - pl.col("total").mean().over("region")).alias("deviation"),
pl.col("total").rank(descending=True).over("region").alias("rank_in_region"),
pl.col("total").cum_sum().over("region").alias("running_total"),
)
print(result)All four columns are computed from the original df. Expressions inside one with_columns call run in parallel and cannot see each other's output. If a later column needs an earlier one, use a second with_columns.
Grouping by several columns
Pass a list, or several arguments, to over.
df = pl.DataFrame(
{
"region": ["north", "north", "north", "south"],
"channel": ["web", "web", "shop", "web"],
"total": [10.0, 30.0, 40.0, 50.0],
}
)
df.with_columns(
pl.col("total").sum().over("region", "channel").alias("group_total")
)Ordering inside a window
Order-dependent expressions such as cum_sum, shift and diff use the current row order of the frame. If the order matters, sort first, or pass order_by to over.
df = pl.DataFrame(
{
"region": ["a", "a", "a", "b", "b"],
"day": [3, 1, 2, 2, 1],
"sales": [30, 10, 20, 200, 100],
}
)
df.with_columns(
pl.col("sales").cum_sum().over("region", order_by="day").alias("running")
)The order_by argument orders the values inside each window for the computation. The output rows stay in the original frame order. Sorting the frame beforehand also works, but it changes the output row order.
Choosing between `over` and `group_by().agg()`
| You need | Use |
|---|---|
| One row per group | `group_by("g").agg(...)` |
| Every row kept, with a group-level value attached | `expr.over("g")` |
| A group summary joined back to the full frame | `over`, not a self-join |
A frequent pandas workaround is to aggregate and then merge the result back onto the original frame. In Polars, over does that in one expression, and it is usually shorter and faster than the join.
Edge cases and common errors
- Null group keys. Rows whose key is null form their own group in Polars, so they receive a value instead of being dropped. pandas
transformdrops them by default (dropna=True) and returns NaN for those rows. Check this when comparing migrated results. - Nulls in the values.
mean,sumandminskip nulls. A group of only nulls gives null formean, and0forsum. - NaN is not null. A float NaN in the data propagates through
mean. Usefill_nan(None)first if you want it treated as missing. The nulls chapter covers this in detail. - Filtered windows. To compute a group value from only some rows, filter inside the expression:
pl.col("total").filter(pl.col("total") > 0).mean().over("region"). Do not filter the frame first, because that would drop rows. - Expecting a Series back.
pl.col("x").over("g")on its own, with no aggregation, returns the values reordered by group and mapped back, which is rarely what you want. Applyoverto an aggregation or a window-style operation such ascum_sumorrank. - Grouping with an expression.
overaccepts expressions as keys, for exampleover(pl.col("ts").dt.year()), which replaces grouping by a derived key in pandas.
Cost of `over`
over is not free. Polars groups the data, computes the expression, and maps the result back to rows. If you use the same grouping in many columns, put them all in one with_columns call. Polars can then share the grouping work between expressions with the same keys. Chaining many separate with_columns calls loses this.
Exercise
A pandas frame has columns store, product and units. You run pdf["share"] = pdf["units"] / pdf.groupby("store")["units"].transform("sum"). Write the Polars equivalent for a frame df, and explain why no join or temporary column is needed.
Show answer
df = df.with_columns((pl.col("units") / pl.col("units").sum().over("store")).alias("share")). The over("store") call computes the sum per store and maps it back to each row of that store, so the division happens row by row inside one expression. Assigning the result back to df is needed because Polars frames are immutable and with_columns returns a new frame.
Exercise
You have columns region, day and sales. Add a column prev_sales holding the previous day's sales within each region, with rows in their original order. Which arguments do you need?
Show answer
df.with_columns(pl.col("sales").shift(1).over("region", order_by="day").alias("prev_sales")). The shift(1) gives the previous value in the window, over("region") restarts it for each region, and order_by="day" defines the order within each window without reordering the output rows. The first day of each region gets null.