polars.Expr.bottom_k#

Expr.bottom_k(
k: int | IntoExprColumn = 5,
*,
nulls_last: bool = False,
maintain_order: bool = False,
multithreaded: bool = True,
) Self[source]#

Return the k smallest elements.

This has time complexity:

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

Number of elements to return.

nulls_last

Place null values last.

maintain_order

Whether the order should be maintained if elements are equal.

multithreaded

Sort using multiple threads.

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       │
└───────┴──────────┘