Convert the Series of type List to a Series of type Struct
Description
Convert the Series of type List to a Series of type Struct
Usage
<Expr>$list$to_struct(
n_field_strategy = deprecated(),
fields = NULL,
upper_bound = NULL
)
Arguments
Details
As of polars 1.3.0, the n_field_strategy
argument is
ignored and deprecated. The fields
needs to be a character
vector or the upper_bound
is regarded as ground truth.
If inferring field length is needed,
<series>$list$to_struct()
can be used, which inspects the
data at runtime.
Value
A polars expression
See Also
-
\
$arr$to_struct() -
\
$list$to_struct()
Examples
library("polars")
df <- pl$DataFrame(n = list(c(0, 1), c(0, 1, 2)))
# Convert list to struct with default field name assignment:
# This will become a struct with 2 fields.
df$select(pl$col("n")$list$to_struct(upper_bound = 2))$unnest("n")
#> shape: (2, 2)
#> ┌─────────┬─────────┐
#> │ field_0 ┆ field_1 │
#> │ --- ┆ --- │
#> │ f64 ┆ f64 │
#> ╞═════════╪═════════╡
#> │ 0.0 ┆ 1.0 │
#> │ 0.0 ┆ 1.0 │
#> └─────────┴─────────┘
# Convert list to struct with field name assignment by
# function/index:
df$select(
pl$col("n")$list$to_struct(
fields = \(idx) paste0("n", idx + 1),
upper_bound = 2
)
)$unnest("n")
#> shape: (2, 2)
#> ┌─────┬─────┐
#> │ n1 ┆ n2 │
#> │ --- ┆ --- │
#> │ f64 ┆ f64 │
#> ╞═════╪═════╡
#> │ 0.0 ┆ 1.0 │
#> │ 0.0 ┆ 1.0 │
#> └─────┴─────┘
# Convert list to struct with field name assignment by
# index from a list of names:
df$select(pl$col("n")$list$to_struct(
fields = c("one", "two", "three"))
)$unnest("n")
#> shape: (2, 3)
#> ┌─────┬─────┬───────┐
#> │ one ┆ two ┆ three │
#> │ --- ┆ --- ┆ --- │
#> │ f64 ┆ f64 ┆ f64 │
#> ╞═════╪═════╪═══════╡
#> │ 0.0 ┆ 1.0 ┆ null │
#> │ 0.0 ┆ 1.0 ┆ 2.0 │
#> └─────┴─────┴───────┘