Skip to content

Return the k largest elements

Description

Non-null elements are always preferred over null elements. 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).

Usage

<Expr>$top_k(k = 5)

Arguments

k Number of elements to return.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(value = c(1, 98, 2, 3, 99, 4))
df$select(
  top_k = pl$col("value")$top_k(k = 3),
  bottom_k = pl$col("value")$bottom_k(k = 3)
)
#> shape: (3, 2)
#> ┌───────┬──────────┐
#> │ top_k ┆ bottom_k │
#> │ ---   ┆ ---      │
#> │ f64   ┆ f64      │
#> ╞═══════╪══════════╡
#> │ 99.0  ┆ 1.0      │
#> │ 98.0  ┆ 2.0      │
#> │ 4.0   ┆ 3.0      │
#> └───────┴──────────┘