Skip to content

Commit 64a01e7

Browse files
authored
feat: Expose descending and nulls last in window order-by (#20919)
1 parent 2352c1e commit 64a01e7

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

Diff for: py-polars/polars/expr/expr.py

+10-2
Original file line numberDiff line numberDiff line change
@@ -3412,6 +3412,8 @@ def over(
34123412
partition_by: IntoExpr | Iterable[IntoExpr],
34133413
*more_exprs: IntoExpr,
34143414
order_by: IntoExpr | Iterable[IntoExpr] | None = None,
3415+
order_by_descending: bool = False,
3416+
order_by_nulls_last: bool = False,
34153417
mapping_strategy: WindowMappingStrategy = "group_to_rows",
34163418
) -> Expr:
34173419
"""
@@ -3431,9 +3433,15 @@ def over(
34313433
column names.
34323434
*more_exprs
34333435
Additional columns to group by, specified as positional arguments.
3434-
order_by:
3436+
order_by
34353437
Order the window functions/aggregations with the partitioned groups by the
34363438
result of the expression passed to `order_by`.
3439+
order_by_descending
3440+
In case 'order_by' is given, indicate whether to order in
3441+
ascending or descending order.
3442+
order_by_nulls_last
3443+
In case 'order_by' is given, indicate whether to order
3444+
the nulls in last position.
34373445
mapping_strategy: {'group_to_rows', 'join', 'explode'}
34383446
- group_to_rows
34393447
If the aggregation results in multiple values, assign them back to their
@@ -3571,7 +3579,7 @@ def over(
35713579
self._pyexpr.over(
35723580
partition_by,
35733581
order_by=order_by,
3574-
order_by_descending=False, # does not work yet
3582+
order_by_descending=order_by_descending,
35753583
order_by_nulls_last=False, # does not work yet
35763584
mapping_strategy=mapping_strategy,
35773585
)

Diff for: py-polars/tests/unit/operations/test_window.py

+2
Original file line numberDiff line numberDiff line change
@@ -487,12 +487,14 @@ def test_window_order_by_8662() -> None:
487487
assert df.with_columns(
488488
x_lag0=pl.col("x").shift(1).over("g"),
489489
x_lag1=pl.col("x").shift(1).over("g", order_by="t"),
490+
x_lag2=pl.col("x").shift(1).over("g", order_by="t", order_by_descending=True),
490491
).to_dict(as_series=False) == {
491492
"g": [1, 1, 1, 1, 2, 2, 2, 2],
492493
"t": [1, 2, 3, 4, 4, 1, 2, 3],
493494
"x": [10, 20, 30, 40, 10, 20, 30, 40],
494495
"x_lag0": [None, 10, 20, 30, None, 10, 20, 30],
495496
"x_lag1": [None, 10, 20, 30, 40, None, 20, 30],
497+
"x_lag2": [20, 30, 40, None, None, 30, 40, 10],
496498
}
497499

498500

0 commit comments

Comments
 (0)