Sub topic 4
Group order and maintain_order
This chapter covers the order of the rows that group_by returns. It assumes you can write a basic group_by(...).agg(...) call, as covered in the previous chapters. Order does not change the numbers in your result. It changes which row appears first, and that matters when you compare outputs, write tests, or build reports.
What Polars promises about order
There are two separate orders in a grouped result:
- The order of the groups (the output rows). By default Polars does not guarantee it. The same query can return groups in a different order on different runs.
- The order of rows inside each group. Polars always keeps these in the order they had in the input frame.
The second guarantee is why first(), last(), and collecting values into a list give stable answers, even when the output rows are shuffled. The first guarantee is missing because Polars builds groups in parallel with a hash table. Promising a fixed order would cost time and memory.
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, but the row order may differ from run to runThe totals are always west 20, east 30, and north 7. Only the order of the three rows can vary. On a small frame you may see the same order many times, and then a different one on a larger frame or another machine. Do not rely on it.
Option 1: maintain_order=True
Passing maintain_order=True makes the groups come out in the order of their first appearance 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 7The input first shows west, then east, then north, so the output rows follow that sequence. west appears again at row 3, but it keeps its first position.
This option has a cost. Polars has to track the first position of every group, which makes the operation slower and uses more memory. It can also rule out some optimizations, such as the streaming engine processing the data in parallel chunks. The cost is small for modest data and noticeable for large data with many groups.
Option 2: sort the result
Often you do not want first-appearance order at all. You want a meaningful order such as alphabetical, or largest total first. Then sorting the result is the better tool, because it gives an order you chose on purpose.
by_name = (
df.group_by("region")
.agg(pl.col("sales").sum().alias("total"))
.sort("region")
)
print(by_name) # east 30, north 7, west 20
by_total = (
df.group_by("region")
.agg(pl.col("sales").sum().alias("total"))
.sort(["total", "region"], descending=[True, False])
)
print(by_total) # east 30, west 20, north 7The second query sorts by total from largest to smallest. It lists region as a second key so that tied totals are always ordered the same way, alphabetically here. Without a tie-breaker, rows with equal totals could still swap places between runs, because the sort only sees the unsorted order the group-by produced.
Sorting costs time too, but it sorts one row per group, not the original rows. For a group-by that reduces millions of rows to a few hundred groups, the sort is cheap.
Order inside each group
Row order inside a group is stable, so order-sensitive aggregations behave predictably.
out = df.group_by("region", maintain_order=True).agg(
pl.col("sales").first().alias("first_sale"),
pl.col("sales").last().alias("last_sale"),
pl.col("sales").alias("all_sales"),
)
print(out)
# west: first 5, last 15, all_sales [5, 15]
# east: first 10, last 20, all_sales [10, 20]
# north: first 7, last 7, all_sales [7]Here first() means the first row of that group in the input, not the smallest value. If you need "the earliest sale", sort the input by a date column before grouping, or use sort_by inside the aggregation:
out = (
df.group_by("region", maintain_order=True)
.agg(pl.col("sales").sort().first().alias("smallest_sale"))
)
print(out) # west 5, east 10, north 7The group-by guarantees input order within groups. It does not guarantee any other order, so you must state it when it matters.
Where the same question appears elsewhere
The order question is not unique to group_by. Several related operations have the same trade-off:
| Operation | Default order behavior | How to control it |
|---|---|---|
| `group_by` | Group order not guaranteed | `maintain_order=True` or `.sort(...)` |
| `unique` | Row order not guaranteed | `maintain_order=True` |
| `partition_by` | Keeps first-appearance order | `maintain_order=False` for speed |
| `over` | Keeps original row order | Nothing to set |
| `join` | Depends on the join type and Polars version | `maintain_order` in recent releases, or sort afterward |
over never reorders rows, because it returns one value per input row. That is one reason to choose it when you want to keep the original layout, as discussed in a later chapter.
For joins, do not assume row order unless the documentation for your installed version says so. Recent Polars releases add a maintain_order argument to join. When you cannot check, sort the result by an explicit key.
Lazy queries
LazyFrame.group_by accepts the same maintain_order argument. The query optimizer does not decide the order for you. Setting the flag or adding a sort has the same meaning as in eager mode.
lazy_out = (
df.lazy()
.group_by("region", maintain_order=True)
.agg(pl.col("sales").sum().alias("total"))
.collect()
)
print(lazy_out) # west 20, east 30, north 7Testing without depending on order
When you test a function that returns a grouped frame, an unstable group order makes the test flaky. You have two clean fixes. One is to sort both frames on a key before comparing. The other is to tell the comparison to ignore row order:
from polars.testing import assert_frame_equal
actual = df.group_by("region").agg(pl.col("sales").sum().alias("total"))
expected = pl.DataFrame({
"region": ["east", "north", "west"],
"total": [30, 7, 20],
})
assert_frame_equal(actual, expected, check_row_order=False)
print("frames match")check_row_order=False makes the test pass whatever order group_by produced, while it still checks the values and column types. Prefer this over adding maintain_order=True only to satisfy a test, since that would slow the production code for no reason.
Choosing an approach
Use this as a rule of thumb:
- If the next step ignores order, such as a join or a plot where you set the axis order, do nothing.
- If a person reads the table, sort it by the column that makes sense to them.
- If you must mirror the input's sequence, such as keeping categories in the order they were first seen, use
maintain_order=True.
Common mistakes
- Treating a lucky order as a guarantee. A script that happens to print groups alphabetically today can print them differently after an upgrade or on bigger data.
- Sorting only by a column with ties. Add a second sort key so ties are stable.
- Using
maintain_order=Trueeverywhere. It is correct but costs speed, so keep it for places that need it. - Confusing group order with in-group order. Rows inside a group stay in input order, but the groups themselves do not unless you ask.
Exercise
A DataFrame has a column "team" with values ["b", "a", "b", "c", "a"] and a column "points" with values [3, 1, 4, 1, 5]. Write a group_by that returns the total points per team with the teams in the order b, a, c, and then one that returns the teams in alphabetical order. Which of the two is cheaper to run on a very large frame with few teams, and why?
Show answer
Use pl.DataFrame({"team": ["b", "a", "b", "c", "a"], "points": [3, 1, 4, 1, 5]}). For first-appearance order: df.groupby("team", maintainorder=True).agg(pl.col("points").sum()) gives b 7, a 6, c 1. For alphabetical order: df.groupby("team").agg(pl.col("points").sum()).sort("team") gives a 6, b 7, c 1. With few teams, sorting the grouped result is very cheap because it only sorts a handful of rows. maintainorder=True makes the group-by itself track first positions for the whole input, which costs more on a large frame, so the sorted version is usually cheaper here.