Skip to content

Unnest the Struct columns of a LazyFrame

Source code

Description

Unnest the Struct columns of a LazyFrame

Usage

<LazyFrame>$unnest(names = NULL)

Arguments

names Names of the struct columns to unnest. If NULL (default), then all "struct" columns are unnested.

Value

A LazyFrame where all "struct" columns are unnested. Non-struct columns are not modified.

Examples

library(polars)

lf = pl$LazyFrame(
  a = 1:5,
  b = c("one", "two", "three", "four", "five"),
  c = 6:10
)$
  select(
  pl$struct("b"),
  pl$struct(c("a", "c"))$alias("a_and_c")
)
lf$collect()
#> shape: (5, 2)
#> ┌───────────┬───────────┐
#> │ b         ┆ a_and_c   │
#> │ ---       ┆ ---       │
#> │ struct[1] ┆ struct[2] │
#> ╞═══════════╪═══════════╡
#> │ {"one"}   ┆ {1,6}     │
#> │ {"two"}   ┆ {2,7}     │
#> │ {"three"} ┆ {3,8}     │
#> │ {"four"}  ┆ {4,9}     │
#> │ {"five"}  ┆ {5,10}    │
#> └───────────┴───────────┘
# by default, all struct columns are unnested
lf$unnest()$collect()
#> shape: (5, 3)
#> ┌───────┬─────┬─────┐
#> │ b     ┆ a   ┆ c   │
#> │ ---   ┆ --- ┆ --- │
#> │ str   ┆ i32 ┆ i32 │
#> ╞═══════╪═════╪═════╡
#> │ one   ┆ 1   ┆ 6   │
#> │ two   ┆ 2   ┆ 7   │
#> │ three ┆ 3   ┆ 8   │
#> │ four  ┆ 4   ┆ 9   │
#> │ five  ┆ 5   ┆ 10  │
#> └───────┴─────┴─────┘
# we can specify specific columns to unnest
lf$unnest("a_and_c")$collect()
#> shape: (5, 3)
#> ┌───────────┬─────┬─────┐
#> │ b         ┆ a   ┆ c   │
#> │ ---       ┆ --- ┆ --- │
#> │ struct[1] ┆ i32 ┆ i32 │
#> ╞═══════════╪═════╪═════╡
#> │ {"one"}   ┆ 1   ┆ 6   │
#> │ {"two"}   ┆ 2   ┆ 7   │
#> │ {"three"} ┆ 3   ┆ 8   │
#> │ {"four"}  ┆ 4   ┆ 9   │
#> │ {"five"}  ┆ 5   ┆ 10  │
#> └───────────┴─────┴─────┘