Sub topic 4
Group order and maintain_order
This chapter assumes you can write group_by(...).agg(...) and know how to use pl.col. It covers a detail that surprises many people: the order of the rows that group_by returns.
Group order is not guaranteed
By default, Polars computes groups in parallel and returns them in whatever order they finish. Running the same query twice can return the same rows in a different order. The values in each row are always correct. Only the row order changes.
import polars as pl
df = pl.DataFrame({
"region": ["west", "east", "west", "east", "north"],
"sales": [5, 10, 15, 20, 7],
})
out = df.group_by("region").agg(pl.col("sales").sum().alias("total"))
print(out) # three rows, in no guaranteed orderIf your code or a test compares this output with a fixed expected result, it can fail at random. The failures are hard to reproduce.
Option 1: sort the result
Sorting by the key gives an order you control and that does not change between runs.
out = (
df.group_by("region")
.agg(pl.col("sales").sum().alias("total"))
.sort("region")
)
print(out) # north 7, east 30 and west 20 sorted as: east, north, westThe rows come out as east (30), north (7), west (20). Use sort when you want alphabetical or numeric order of the keys, or order by an aggregated value such as sort("total", descending=True).
Option 2: maintain_order=True
Pass maintain_order=True to return groups in the order each key first appears in the input.
out = df.group_by("region", maintain_order=True).agg(
pl.col("sales").sum().alias("total")
)
print(out) # west 20, east 30, north 7Here west comes first because it appears in row 0. east appears next in row 1, and north last in row 4.
Order inside each group
The order of rows inside a group is always the original row order, whether or not you set maintain_order. That makes order-sensitive aggregations deterministic.
out = df.group_by("region").agg(
pl.col("sales").first().alias("first_sale"),
pl.col("sales").last().alias("last_sale"),
).sort("region")
print(out) # east: 10, 20; north: 7, 7; west: 5, 15first() and last() return the same values on every run. Only the order of the output rows can vary, which is why the sort is there.
Choosing between the options
| Need | Use | Cost |
|---|---|---|
| Any order is fine, for example before a join or a plot | Nothing extra | Fastest |
| Keys in sorted order | `.sort(key)` after `agg` | One sort of the (usually small) result |
| Keys in order of first appearance | `maintain_order=True` | Slower on large inputs and can limit optimizations |
Common errors
- Writing a test that compares a
group_byresult to an expected DataFrame without sorting both sides. - Adding
maintain_order=Trueeverywhere "just in case". This slows large queries when the order is never used. - Expecting
maintain_order=Trueto sort. It keeps first-appearance order, which is not sorted order.
Exercise
A DataFrame has a team column with the values ["b", "a", "b", "c", "a"]. You run df.group_by("team", maintain_order=True).agg(pl.len().alias("n")). In what order do the teams appear, and how would you get them in alphabetical order instead?
Show answer
The teams appear in order of first appearance: b, a, c. For alphabetical order, drop maintain_order=True (or keep it) and add .sort("team") after agg, which gives a, b, c.