Sub topic 11
Window mapping strategies
The previous chapters showed over computing a per-group value and repeating it on every row. That behavior is one of three ways Polars can map a per-group result back onto a DataFrame. This chapter covers all three, the mapping_strategy argument that selects between them, and how to pick one.
This chapter assumes you can write over expressions and know that sum().over("region") keeps the DataFrame's height. All examples use this DataFrame:
import polars as pl
df = pl.DataFrame({
"region": ["east", "east", "west", "west", "west"],
"product": ["a", "b", "a", "b", "b"],
"sales": [10, 20, 5, 15, 25],
})What a mapping strategy decides
An expression inside over runs once per group. Each group's result can have a different length: one value for sum(), the group's own length for sort(), or something else for unique(). The mapping strategy decides how those per-group results become a column.
The strategy is a keyword argument of over:
pl.col("sales").sum().over("region", mapping_strategy="group_to_rows")The three values are "group_to_rows" (the default), "join", and "explode".
group_to_rows: results go back to the original positions
With group_to_rows, Polars writes each group's result into the row positions that group occupied in the original DataFrame. The output column has the same length and row order as the input.
- If the expression returns one value per group, that value is repeated on every row of the group. This is the
sum().over(...)behavior you already know. - If the expression returns one value per row of the group, the values are placed on the group's rows in the order produced.
The second case is easy to overlook. Sorting inside a window does not reorder the DataFrame. It reorders the values among the rows of each group:
out = df.with_columns(
pl.col("sales").sort(descending=True).over("region").alias("sales_desc")
)
print(out)
# row 0 (east): sales 10, sales_desc 20
# row 1 (east): sales 20, sales_desc 10
# rows 2-4 (west): sales 5, 15, 25 -> sales_desc 25, 15, 5The sales_desc column is a sorted copy of each group's values, laid over the group's own rows. Row order and the other columns do not change. This is useful when you want "the group's values in a different order" next to the original data. It is a poor fit if you expected the whole table to be sorted.
If the expression returns neither one value nor one value per group row, group_to_rows cannot place the result and Polars raises an error. This is the case the other two strategies exist for.
join: each row receives the group's whole result
With join, the per-group result is collected into a list, and that list is attached to every row of the group, as in a join on the group key. The result has the original height and row order, and its dtype is List. Because each row gets the entire result, the length of the result no longer has to match anything.
Here every row gets the distinct products sold in its region:
out = df.with_columns(
pl.col("product")
.unique(maintain_order=True)
.over("region", mapping_strategy="join")
.alias("region_products")
)
print(out)
# every row has region_products = ["a", "b"]
# dtype of region_products: List(String)East has two rows and two distinct products, so group_to_rows would happen to fit there. West has three rows and two distinct products, so with the default strategy this expression fails. With join, every row of both regions receives its group's list.
The sorted example also behaves differently under join:
out = df.with_columns(
pl.col("sales").sort(descending=True)
.over("region", mapping_strategy="join")
.alias("sales_list")
)
print(out)
# east rows: [20, 10]
# west rows: [25, 15, 5]Every row carries a list of its group's sorted values. Use join when you want the group-level collection on each row, for example to compute list.contains or list lengths later. If you only need a scalar per group, the default is simpler and does not create list columns.
explode: group order, no mapping back
With explode, Polars does not map results back to the original rows at all. It concatenates the per-group results, as if you had run group_by(...).agg(...) and then exploded the list column. The rows come out grouped together, so the original row order is lost.
Use it in select, where you are building a new frame:
out = df.select(
pl.col("region"),
pl.col("sales").sort(descending=True).over("region", mapping_strategy="explode"),
)
print(out)
# values: 20, 10 for east and 25, 15, 5 for west
# rows are contiguous per group; the order of the two groups is not guaranteedHere region comes from the original row order, while the sales column is in group order, so the two columns would not line up. The example above shows the hazard. It runs, but the pairing between region and sales is not meaningful. In practice, either select only expressions that all use explode, or add the key into the same windowed result.
out = df.select(
pl.col("region").over("region", mapping_strategy="explode"),
pl.col("sales").sort(descending=True).over("region", mapping_strategy="explode"),
)
print(out)
# each region value lines up with its own group's sorted salesBoth columns now use the same group order, so they stay aligned. explode skips the work of mapping values back to row positions, so it can be faster on large data. You pay for that with lost row order.
Comparing the three strategies
| Strategy | Output height | Row order | Per-group result length | Result dtype |
|---|---|---|---|---|
| `group_to_rows` | Same as input | Original | One value, or one per group row | Same as expression |
| `join` | Same as input | Original | Any | List |
| `explode` | Sum of group result lengths | Grouped | Any | Same as expression |
Common mistakes
- Expecting
sort().over(...)to sort the DataFrame. Under the default strategy it rearranges values only inside each group's row positions. To sort rows, callDataFrame.sort. - Using
explodeinsidewith_columns. The new column's values are in group order, but the other columns keep the original order, so rows silently mismatch. - Reaching for
joinwhen you want a scalar. You get a list column on every row, which then needslist.first()or a similar call to unwrap. Use an aggregation such assum()orfirst()with the default strategy instead. - Assuming group order under
explode. Sort the output explicitly if you need a deterministic order.
Summary
The default group_to_rows strategy covers most window work: per-group scalars, ranks, running totals, and shifted values all return one value per group or one per row. Use join when each row should carry a variable-length result as a list. Use explode only when you are building a new, grouped frame and do not need the original order.
Exercise
For the DataFrame in this chapter, you want every row to show the list of its region's sales values sorted ascending, and you must keep the original row order. Which mapping strategy and what dtype does the new column have? Write the expression.
Show answer
Use mappingstrategy="join", which gives a List column (List of Int64 here). For example: df.withcolumns(pl.col("sales").sort().over("region", mappingstrategy="join").alias("sortedsales")). East rows get [10, 20] and west rows get [5, 15, 25], and the five rows stay in their original order.
Exercise
Why is df.with_columns(pl.col("sales").sort(descending=True).over("region", mapping_strategy="explode")) risky, and what is a safer way to get the same sorted values per group?
Show answer
With explode, the new sales column is in group order, but the other columns keep the original row order, so rows can silently mismatch. A safer option is the default grouptorows strategy, which keeps the values on the group's own rows, or use select with every column windowed under explode so they share the same order.