Sub topic 11
Window mapping strategies
This chapter assumes you know over from the earlier chapter on per-group values. You should also be comfortable with with_columns and select. Here you will learn how over places its results back into the table, and how to change that with mapping_strategy.
Why mapping matters
An expression inside over can return one value per group (like sum) or several values per group (like sort). Polars has to decide how to line those results up with the rows of the DataFrame. The mapping_strategy argument sets that choice.
| Strategy | Result shape | Typical use |
|---|---|---|
| `"group_to_rows"` (default) | One value per original row, in original row positions | Ranking, sorting, shifting, cumulative values |
| `"join"` | One list per row, the same list repeated for every row of the group | Keeping the whole group's values next to each row |
| `"explode"` | Values laid out group by group, no repeating | Fast reordering when row order does not matter |
Setup
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"sales": [10, 20, 5, 15, 25],
})group_to_rows: the default
With group_to_rows, results are written back into the positions the group's rows already occupy. A scalar such as a sum is repeated on each row. A sequence of values must have the same length as the group.
out = df.with_columns(
pl.col("sales").sort(descending=True).over("region").alias("sorted_in_group")
)
print(out)The sorted values stay inside each group's own row positions. The east rows get 20 then 10. The west rows get 25, 15, then 5. The row order and the height (5 rows) do not change.
join: one list per row
With join, each row receives the group's whole result as a list.
out = df.with_columns(
pl.col("sales")
.sort(descending=True)
.over("region", mapping_strategy="join")
.alias("group_sales_desc")
)
print(out)Every east row holds [20, 10]. Every west row holds [25, 15, 5]. The column has the List data type, so it uses more memory than a plain column. Use it only when you need the whole group beside each row, for example to apply a list operation afterward.
explode: grouped output without alignment
With explode, Polars skips the work of mapping values back to the original row positions. The output is the group results laid end to end, so rows end up grouped together by region. The original order is not kept.
out = df.select(
pl.col("sales")
.sort(descending=True)
.over("region", mapping_strategy="explode")
)
print(out)Use select here and do not put other, non-windowed columns beside it. Those columns keep the original order, so they would no longer match the exploded one. This strategy is the fastest of the three for this kind of work, which is its main reason to exist.
Common errors
- Length mismatch. Under
group_to_rows, an expression that returns a different number of values than the group has rows raises an error. Reduce it to a scalar or usejoin. - Unexpected list column. If you see a List column, check whether you passed
mapping_strategy="join". - Misaligned columns. Mixing
explodeoutput with ordinary columns in oneselectgives rows that do not belong together.
Exercise
You want each row of df to carry the full list of its region's sales values, in original order. Which mapping strategy do you use, and what data type does the new column have?
Show answer
Use mappingstrategy="join", for example pl.col("sales").over("region", mappingstrategy="join"). The new column has the List data type, and every row of a group holds the same list.