Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix DataFrame.top_k not handling nulls correctly #17239

Merged
merged 3 commits into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 0 additions & 12 deletions crates/polars-core/src/frame/top_k.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,7 @@
use smartstring::alias::String as SmartString;

use super::*;
use crate::prelude::sort::arg_bottom_k::_arg_bottom_k;

impl DataFrame {
pub fn top_k(
&self,
k: usize,
by_column: impl IntoVec<SmartString>,
sort_options: SortMultipleOptions,
) -> PolarsResult<DataFrame> {
let by_column = self.select_series(by_column)?;
self.bottom_k_impl(k, by_column, sort_options.with_order_reversed())
}

pub(crate) fn bottom_k_impl(
&self,
k: usize,
Expand Down
10 changes: 7 additions & 3 deletions crates/polars-lazy/src/frame/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -366,8 +366,11 @@ impl LazyFrame {
sort_options: SortMultipleOptions,
) -> Self {
// this will optimize to top-k
self.sort_by_exprs(by_exprs, sort_options.with_order_reversed())
.slice(0, k)
self.sort_by_exprs(
by_exprs,
sort_options.with_order_reversed().with_nulls_last(true),
)
.slice(0, k)
}

pub fn bottom_k<E: AsRef<[Expr]>>(
Expand All @@ -377,7 +380,8 @@ impl LazyFrame {
sort_options: SortMultipleOptions,
) -> Self {
// this will optimize to bottom-k
self.sort_by_exprs(by_exprs, sort_options).slice(0, k)
self.sort_by_exprs(by_exprs, sort_options.with_nulls_last(true))
.slice(0, k)
}

/// Reverse the `DataFrame` from top to bottom.
Expand Down
6 changes: 3 additions & 3 deletions py-polars/tests/unit/operations/test_top_k.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ def test_top_k() -> None:
# dataframe
df = pl.DataFrame(
{
"a": [1, 2, 3, 4, 2, 2],
"b": [3, 2, 1, 4, 3, 2],
"a": [1, 2, 3, 4, 2, 2, None],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"a": [1, 2, 3, 4, 2, 2, None],
"a": [1, 2, 3, 4, 2, 2, None],

"b": [None, 2, 1, 4, 3, 2, None],
}
)

Expand All @@ -81,7 +81,7 @@ def test_top_k() -> None:

assert_frame_equal(
df.top_k(3, by=["a", "b"], reverse=True),
pl.DataFrame({"a": [1, 2, 2], "b": [3, 2, 2]}),
pl.DataFrame({"a": [1, 2, 2], "b": [None, 2, 2]}),
check_row_order=False,
)
assert_frame_equal(
Expand Down
Loading