Skip to content

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

Source code

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

n_field_strategy [Deprecated] Ignored.
fields [Experimental] NULL (default) or character vector of field names, or a function that takes an integer index and returns character. If the name and number of the desired fields is known in advance, character vector of field names can be given, which will be assigned by index. Otherwise, to dynamically assign field names, a custom function can be used; if neither are set, fields will be field_0, field_1… See the examples for details.
upper_bound Single positive integer value or NULL (default). A polars expression needs to be able to evaluate the output datatype at all times, so the caller must provide an upper bound of the number of struct fields that will be created if fields is not a character vector of field names.

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   │
#> └─────┴─────┴───────┘