Skip to content

Generate a row index

Source code

Description

[Experimental] The length of the returned sequence will match the context length. If you would like to generate sequences with custom offsets / length / step size / datatypes, it is recommended to use pl$int_range() instead.

Usage

pl$row_index(name = "index")

Arguments

name Name of the returned column.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(x = c("A", "A", "B", "B", "B"))
df$with_columns(pl$row_index(), pl$row_index("another_index"))
#> shape: (5, 3)
#> ┌─────┬───────┬───────────────┐
#> │ x   ┆ index ┆ another_index │
#> │ --- ┆ ---   ┆ ---           │
#> │ str ┆ i64   ┆ i64           │
#> ╞═════╪═══════╪═══════════════╡
#> │ A   ┆ 0     ┆ 0             │
#> │ A   ┆ 1     ┆ 1             │
#> │ B   ┆ 2     ┆ 2             │
#> │ B   ┆ 3     ┆ 3             │
#> │ B   ┆ 4     ┆ 4             │
#> └─────┴───────┴───────────────┘
df$group_by("x")$agg(pl$row_index())$sort("x")
#> shape: (2, 2)
#> ┌─────┬───────────┐
#> │ x   ┆ index     │
#> │ --- ┆ ---       │
#> │ str ┆ list[i64] │
#> ╞═════╪═══════════╡
#> │ A   ┆ [0, 1]    │
#> │ B   ┆ [0, 1, 2] │
#> └─────┴───────────┘
df$select(pl$row_index())
#> shape: (5, 1)
#> ┌───────┐
#> │ index │
#> │ ---   │
#> │ i64   │
#> ╞═══════╡
#> │ 0     │
#> │ 1     │
#> │ 2     │
#> │ 3     │
#> │ 4     │
#> └───────┘