Skip to content

Commit

Permalink
fix: Bug fix in existing fast path for sorted series (#20004)
Browse files Browse the repository at this point in the history
  • Loading branch information
siddharth-vi authored Nov 26, 2024
1 parent d9ea1d8 commit 899881a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
2 changes: 1 addition & 1 deletion crates/polars-core/src/chunked_array/ops/sort/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ macro_rules! sort_with_fast_path {
// if the nulls are already last we can clone
if $options.nulls_last && $ca.get($ca.len() - 1).is_none() ||
// if the nulls are already first we can clone
$ca.get(0).is_none()
(!$options.nulls_last && $ca.get(0).is_none())
{
return $ca.clone();
}
Expand Down
27 changes: 23 additions & 4 deletions py-polars/tests/unit/operations/test_sort.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from datetime import date, datetime
from typing import TYPE_CHECKING, Any
from typing import TYPE_CHECKING, Any, Callable

import pytest
from hypothesis import given
Expand Down Expand Up @@ -163,11 +163,30 @@ def test_sort_by_exprs() -> None:
assert out.to_list() == [1, -1, 2, -2]


def test_arg_sort_nulls() -> None:
@pytest.mark.parametrize(
("sort_function", "expected"),
[
(lambda x: x, ([0, 1, 2, 3, 4], [3, 4, 0, 1, 2])),
(
lambda x: x.sort(descending=False, nulls_last=True),
([0, 1, 2, 3, 4], [3, 4, 0, 1, 2]),
),
(
lambda x: x.sort(descending=False, nulls_last=False),
([2, 3, 4, 0, 1], [0, 1, 2, 3, 4]),
),
],
)
def test_arg_sort_nulls(
sort_function: Callable[[pl.Series], pl.Series],
expected: tuple[list[int], list[int]],
) -> None:
a = pl.Series("a", [1.0, 2.0, 3.0, None, None])

assert a.arg_sort(nulls_last=True).to_list() == [0, 1, 2, 3, 4]
assert a.arg_sort(nulls_last=False).to_list() == [3, 4, 0, 1, 2]
a = sort_function(a)

assert a.arg_sort(nulls_last=True).to_list() == expected[0]
assert a.arg_sort(nulls_last=False).to_list() == expected[1]

res = a.to_frame().sort(by="a", nulls_last=False).to_series().to_list()
assert res == [None, None, 1.0, 2.0, 3.0]
Expand Down

0 comments on commit 899881a

Please sign in to comment.