polars.Expr.top_k#

Expr.top_k(k: int | IntoExprColumn = 5) Self[source]#

Return the k largest elements.

This has time complexity:

\[\begin{split}O(n + k \\log{}n - \frac{k}{2})\end{split}\]
Parameters:
k

Number of elements to return.

See also

bottom_k

Examples

>>> df = pl.DataFrame(
...     {
...         "value": [1, 98, 2, 3, 99, 4],
...     }
... )
>>> df.select(
...     [
...         pl.col("value").top_k().alias("top_k"),
...         pl.col("value").bottom_k().alias("bottom_k"),
...     ]
... )
shape: (5, 2)
┌───────┬──────────┐
│ top_k ┆ bottom_k │
│ ---   ┆ ---      │
│ i64   ┆ i64      │
╞═══════╪══════════╡
│ 99    ┆ 1        │
│ 98    ┆ 2        │
│ 4     ┆ 3        │
│ 3     ┆ 4        │
│ 2     ┆ 98       │
└───────┴──────────┘