Skip to content

Decompose struct columns into separate columns for each of their fields

Source code

Description

The new columns will be inserted at the location of the struct column.

Usage

<DataFrame>$unnest(..., separator = NULL)

Arguments

\<dynamic-dots\> Name of the struct column(s) or selectors that should be unnested.
separator NULL (default) or single string. Rename output column names as combination of the struct column name, name separator and field name.

Value

A polars DataFrame

Examples

library("polars")

df <- pl$DataFrame(
  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")
)
df
#> 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}    │
#> └───────────┴───────────┘
df$unnest("a_and_c")
#> 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  │
#> └───────────┴─────┴─────┘
df$unnest("a_and_c", separator = ":")
#> shape: (5, 3)
#> ┌───────────┬───────────┬───────────┐
#> │ b         ┆ a_and_c:a ┆ a_and_c:c │
#> │ ---       ┆ ---       ┆ ---       │
#> │ struct[1] ┆ i32       ┆ i32       │
#> ╞═══════════╪═══════════╪═══════════╡
#> │ {"one"}   ┆ 1         ┆ 6         │
#> │ {"two"}   ┆ 2         ┆ 7         │
#> │ {"three"} ┆ 3         ┆ 8         │
#> │ {"four"}  ┆ 4         ┆ 9         │
#> │ {"five"}  ┆ 5         ┆ 10        │
#> └───────────┴───────────┴───────────┘