Skip to content

Commit

Permalink
feat: Expose descending and nulls last in window order-by (#20919)
Browse files Browse the repository at this point in the history
  • Loading branch information
ritchie46 authored Jan 26, 2025
1 parent 2352c1e commit 64a01e7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
12 changes: 10 additions & 2 deletions py-polars/polars/expr/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -3412,6 +3412,8 @@ def over(
partition_by: IntoExpr | Iterable[IntoExpr],
*more_exprs: IntoExpr,
order_by: IntoExpr | Iterable[IntoExpr] | None = None,
order_by_descending: bool = False,
order_by_nulls_last: bool = False,
mapping_strategy: WindowMappingStrategy = "group_to_rows",
) -> Expr:
"""
Expand All @@ -3431,9 +3433,15 @@ def over(
column names.
*more_exprs
Additional columns to group by, specified as positional arguments.
order_by:
order_by
Order the window functions/aggregations with the partitioned groups by the
result of the expression passed to `order_by`.
order_by_descending
In case 'order_by' is given, indicate whether to order in
ascending or descending order.
order_by_nulls_last
In case 'order_by' is given, indicate whether to order
the nulls in last position.
mapping_strategy: {'group_to_rows', 'join', 'explode'}
- group_to_rows
If the aggregation results in multiple values, assign them back to their
Expand Down Expand Up @@ -3571,7 +3579,7 @@ def over(
self._pyexpr.over(
partition_by,
order_by=order_by,
order_by_descending=False, # does not work yet
order_by_descending=order_by_descending,
order_by_nulls_last=False, # does not work yet
mapping_strategy=mapping_strategy,
)
Expand Down
2 changes: 2 additions & 0 deletions py-polars/tests/unit/operations/test_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,12 +487,14 @@ def test_window_order_by_8662() -> None:
assert df.with_columns(
x_lag0=pl.col("x").shift(1).over("g"),
x_lag1=pl.col("x").shift(1).over("g", order_by="t"),
x_lag2=pl.col("x").shift(1).over("g", order_by="t", order_by_descending=True),
).to_dict(as_series=False) == {
"g": [1, 1, 1, 1, 2, 2, 2, 2],
"t": [1, 2, 3, 4, 4, 1, 2, 3],
"x": [10, 20, 30, 40, 10, 20, 30, 40],
"x_lag0": [None, 10, 20, 30, None, 10, 20, 30],
"x_lag1": [None, 10, 20, 30, 40, None, 20, 30],
"x_lag2": [20, 30, 40, None, None, 30, 40, 10],
}


Expand Down

0 comments on commit 64a01e7

Please sign in to comment.