Skip to content

Convert the Series of type Array to a Series of type Struct

Source code

Description

Convert the Series of type Array to a Series of type Struct

Usage

<Expr>$arr$to_struct(fields = NULL)

Arguments

fields [Experimental] NULL (default) or a character vector of field names. If NULL is used, names are generated from the fixed array width.

Value

A polars expression

Examples

library("polars")

df <- pl$DataFrame(
  n = list(c(0, 1, 2), c(3, 4, 5)),
  .schema_overrides = list(n = pl$Array(pl$Int8, 3))
)

df$with_columns(struct = pl$col("n")$arr$to_struct())
#> shape: (2, 2)
#> ┌──────────────┬───────────┐
#> │ n            ┆ struct    │
#> │ ---          ┆ ---       │
#> │ array[i8, 3] ┆ struct[3] │
#> ╞══════════════╪═══════════╡
#> │ [0, 1, 2]    ┆ {0,1,2}   │
#> │ [3, 4, 5]    ┆ {3,4,5}   │
#> └──────────────┴───────────┘
# Convert array to struct with field name assignment by index from character:
df$select(pl$col("n")$arr$to_struct(c("a", "b", "c")))$unnest("n")
#> shape: (2, 3)
#> ┌─────┬─────┬─────┐
#> │ a   ┆ b   ┆ c   │
#> │ --- ┆ --- ┆ --- │
#> │ i8  ┆ i8  ┆ i8  │
#> ╞═════╪═════╪═════╡
#> │ 0   ┆ 1   ┆ 2   │
#> │ 3   ┆ 4   ┆ 5   │
#> └─────┴─────┴─────┘