Skip to content

Slice every sub-list

Description

This extracts length values at most, starting at index offset. This can return less than length values if length is larger than the number of values.

Usage

<Expr>$list$slice(offset, length = NULL)

Arguments

offset Start index. Negative indexing is supported. Can be an Expr. Strings are parsed as column names.
length Length of the slice. If NULL (default), the slice is taken to the end of the list. Can be an Expr. Strings are parsed as column names.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(
  s = list(1:4, c(10L, 2L, 1L)),
  idx_off = 1:2,
  len = c(4, 1)
)
df$with_columns(
  slice_by_expr = pl$col("s")$list$slice("idx_off", "len"),
  slice_by_lit = pl$col("s")$list$slice(2, 3)
)
#> shape: (2, 5)
#> ┌─────────────┬─────────┬─────┬───────────────┬──────────────┐
#> │ s           ┆ idx_off ┆ len ┆ slice_by_expr ┆ slice_by_lit │
#> │ ---         ┆ ---     ┆ --- ┆ ---           ┆ ---          │
#> │ list[i32]   ┆ i32     ┆ f64 ┆ list[i32]     ┆ list[i32]    │
#> ╞═════════════╪═════════╪═════╪═══════════════╪══════════════╡
#> │ [1, 2, … 4] ┆ 1       ┆ 4.0 ┆ [2, 3, 4]     ┆ [3, 4]       │
#> │ [10, 2, 1]  ┆ 2       ┆ 1.0 ┆ [1]           ┆ [1]          │
#> └─────────────┴─────────┴─────┴───────────────┴──────────────┘