polars.Expr.list.to_struct#

Expr.list.to_struct(
n_field_strategy: ListToStructWidthStrategy | None = None,
fields: Sequence[str] | Callable[[int], str] | None = None,
upper_bound: int | None = None,
) Expr[source]#

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

Parameters:
n_field_strategy{‘first_non_null’, ‘max_width’}

Deprecated and ignored.

fields

If the name and number of the desired fields is known in advance a list 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 .. field_n.

upper_bound

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 sequence of field names.

.. versionchanged: 1.33.0

The n_field_strategy parameter is ignored and deprecated. The fields needs to be a sequence of field names or the upper bound is regarded as ground truth.

Examples

Convert list to struct with default field name assignment:

>>> df = pl.DataFrame({"n": [[0, 1], [0, 1, 2]]})
>>> df.with_columns(
...     struct=pl.col("n").list.to_struct(upper_bound=2)
... )  
shape: (2, 2)
┌───────────┬───────────┐
│ n         ┆ struct    │
│ ---       ┆ ---       │
│ list[i64] ┆ struct[2] │ # <- struct with 2 fields
╞═══════════╪═══════════╡
│ [0, 1]    ┆ {0,1}     │ # OK
│ [0, 1, 2] ┆ {0,1}     │ # NOT OK - last value missing
└───────────┴───────────┘

Convert list to struct with field name assignment by function/index:

>>> df = pl.DataFrame({"n": [[0, 1], [2, 3]]})
>>> df.select(
...     pl.col("n").list.to_struct(fields=lambda idx: f"n{idx}", upper_bound=2)
... ).rows(named=True)  
[{'n': {'n0': 0, 'n1': 1}}, {'n': {'n0': 2, 'n1': 3}}]

Convert list to struct with field name assignment by index from a list of names:

>>> df.select(pl.col("n").list.to_struct(fields=["one", "two"])).rows(
...     named=True
... )
[{'n': {'one': 0, 'two': 1}}, {'n': {'one': 2, 'two': 3}}]