Skip to content

Add a row index as the first column in the DataFrame

Description

Add a row index as the first column in the DataFrame

Usage

<DataFrame>$with_row_index(name = "index", offset = 0)

Arguments

name Name of the index column.
offset Start the index at this offset. Cannot be negative.

Value

A polars DataFrame

Examples

library("polars")

df <- pl$DataFrame(x = c(1, 3, 5), y = c(2, 4, 6))
df$with_row_index()
#> shape: (3, 3)
#> ┌───────┬─────┬─────┐
#> │ index ┆ x   ┆ y   │
#> │ ---   ┆ --- ┆ --- │
#> │ u32   ┆ f64 ┆ f64 │
#> ╞═══════╪═════╪═════╡
#> │ 0     ┆ 1.0 ┆ 2.0 │
#> │ 1     ┆ 3.0 ┆ 4.0 │
#> │ 2     ┆ 5.0 ┆ 6.0 │
#> └───────┴─────┴─────┘
df$with_row_index("id", offset = 1000)
#> shape: (3, 3)
#> ┌──────┬─────┬─────┐
#> │ id   ┆ x   ┆ y   │
#> │ ---  ┆ --- ┆ --- │
#> │ u32  ┆ f64 ┆ f64 │
#> ╞══════╪═════╪═════╡
#> │ 1000 ┆ 1.0 ┆ 2.0 │
#> │ 1001 ┆ 3.0 ┆ 4.0 │
#> │ 1002 ┆ 5.0 ┆ 6.0 │
#> └──────┴─────┴─────┘
# An index column can also be created using the expressions int_range()
# and len()$
df$with_columns(
  index = pl$int_range(pl$len(), dtype = pl$UInt32)
)
#> shape: (3, 3)
#> ┌─────┬─────┬───────┐
#> │ x   ┆ y   ┆ index │
#> │ --- ┆ --- ┆ ---   │
#> │ f64 ┆ f64 ┆ u32   │
#> ╞═════╪═════╪═══════╡
#> │ 1.0 ┆ 2.0 ┆ 0     │
#> │ 3.0 ┆ 4.0 ┆ 1     │
#> │ 5.0 ┆ 6.0 ┆ 2     │
#> └─────┴─────┴───────┘