polars.Series.top_k_by#

Series.top_k_by(
by: IntoExpr | Iterable[IntoExpr],
k: int = 5,
*,
reverse: bool | Sequence[bool] = False,
) Series[source]#

Return the k largest elements of the by column.

Non-null elements are always preferred over null elements, regardless of the value of reverse. The output is not guaranteed to be in any particular order, call sort() after this function if you wish the output to be sorted.

This has time complexity:

\[O(n \log{n})\]
Parameters:
by

Column used to determine the largest elements. Accepts expression input. Strings are parsed as column names.

k

Number of elements to return.

reverse

Consider the k smallest elements of the by column (instead of the k largest). This can be specified per column by passing a sequence of booleans.

Examples

>>> s = pl.Series("a", [2, 5, 1, 4, 3])
>>> s.top_k_by("a", 3)
shape: (3,)
Series: 'a' [i64]
[
    5
    4
    3
]