Skip to content

Commit aa5d073

Browse files
authored
fix: Incorrect sorted fast-path returning nan for grouped max (#28129)
1 parent a2f2559 commit aa5d073

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

‎crates/polars-core/src/frame/group_by/aggregations/mod.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -632,8 +632,12 @@ where
632632
}
633633

634634
pub(crate) unsafe fn agg_max(&self, groups: &GroupsType) -> Series {
635-
// faster paths
636-
if !self.has_nulls() || matches!(groups, GroupsType::Slice { .. }) {
635+
// Sorted fast-path. We skip this for floats because the largest value might be NaN, which
636+
// max is supposed to skip unless everything is NaN. We would need an
637+
// agg_first_non_null_non_nan.
638+
if (!self.has_nulls() || matches!(groups, GroupsType::Slice { .. }))
639+
&& !T::Native::is_float()
640+
{
637641
match self.is_sorted_flag() {
638642
IsSorted::Ascending => return self.clone().into_series().agg_last_non_null(groups),
639643
IsSorted::Descending => {

‎py-polars/tests/unit/operations/test_group_by.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3164,3 +3164,10 @@ def test_group_by_when_then_with_mutated_idxs() -> None:
31643164
}
31653165
),
31663166
)
3167+
3168+
3169+
def test_group_by_max_sorted_nan_28121() -> None:
3170+
df = pl.DataFrame({"g": [1, 1, 1], "x": [1.0, 2.0, float("nan")]}).sort("x")
3171+
out = df.group_by("g").agg(pl.col("x").max())
3172+
expected = pl.DataFrame({"g": [1], "x": [2.0]})
3173+
assert_frame_equal(out, expected)

0 commit comments

Comments
 (0)