Skip to content

Commit 414c51c

Browse files
committed
feat: add top_k
1 parent 8c02165 commit 414c51c

File tree

2 files changed

+12
-3
lines changed

2 files changed

+12
-3
lines changed

narwhals_daft/dataframe.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
ValidateBackendVersion,
1212
Version,
1313
check_column_names_are_unique,
14+
extend_bool,
1415
generate_temporary_column_name,
1516
not_implemented,
1617
parse_columns_to_drop,
@@ -26,7 +27,7 @@
2627
from narwhals_daft.utils import evaluate_exprs, lit, native_to_narwhals_dtype
2728

2829
if TYPE_CHECKING:
29-
from collections.abc import Iterator, Mapping, Sequence
30+
from collections.abc import Iterable, Iterator, Mapping, Sequence
3031
from types import ModuleType
3132

3233
from narwhals._compliant.typing import CompliantDataFrameAny
@@ -229,6 +230,16 @@ def sort(
229230
)
230231
)
231232

233+
def top_k(
234+
self, k: int, *, by: Iterable[str], reverse: bool | Sequence[bool]
235+
) -> Self:
236+
descending = [not x for x in extend_bool(reverse, len(list(by)))]
237+
return self._with_native(
238+
self._native_frame.sort(list(by), desc=descending, nulls_first=False).limit(
239+
k
240+
)
241+
)
242+
232243
def drop_nulls(self, subset: Sequence[str] | None) -> Self:
233244
if subset:
234245
return self._with_native(self._native_frame.drop_null(*subset))

run_tests.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,6 @@
125125
"test_to_datetime_infer_fmt",
126126
"test_to_datetime_infer_fmt_from_date",
127127
"test_to_datetime_tz_aware",
128-
"test_top_k",
129-
"test_top_k_by_multiple",
130128
"test_truncate",
131129
"test_truncate_invalid_interval",
132130
"test_truncate_invalid_multiple",

0 commit comments

Comments
 (0)