polars.Expr.arr.to_struct#

Expr.arr.to_struct(fields: Sequence[str] | None = None) → Expr[source]#

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

Parameters:
fields

Field names to use for the output. The number of names given must match the width of the input array. If unset, the fields will be named as “field_0”, “field_1” .. “field_n”.

Examples

>>> df = pl.DataFrame(
...     {
...         "c": pl.Series(
...             [
...                 [1, 0, 0],
...                 [0, 1, 0],
...                 [0, 0, 1],
...                 [None, None, None],
...                 None,
...             ],
...             dtype=pl.Array(pl.Int64, 3),
...         )
...     }
... )
>>> print(result := df.with_columns(c_struct=pl.col("c").arr.to_struct()))
shape: (5, 2)
┌────────────────────┬──────────────────┐
│ c                  ┆ c_struct         │
│ ---                ┆ ---              │
│ array[i64, 3]      ┆ struct[3]        │
╞════════════════════╪══════════════════╡
│ [1, 0, 0]          ┆ {1,0,0}          │
│ [0, 1, 0]          ┆ {0,1,0}          │
│ [0, 0, 1]          ┆ {0,0,1}          │
│ [null, null, null] ┆ {null,null,null} │
│ null               ┆ null             │
└────────────────────┴──────────────────┘
>>> print(result["c_struct"].struct.unnest())
shape: (5, 3)
┌─────────┬─────────┬─────────┐
│ field_0 ┆ field_1 ┆ field_2 │
│ ---     ┆ ---     ┆ ---     │
│ i64     ┆ i64     ┆ i64     │
╞═════════╪═════════╪═════════╡
│ 1       ┆ 0       ┆ 0       │
│ 0       ┆ 1       ┆ 0       │
│ 0       ┆ 0       ┆ 1       │
│ null    ┆ null    ┆ null    │
│ null    ┆ null    ┆ null    │
└─────────┴─────────┴─────────┘

Convert to struct with custom field names:

>>> print(
...     result := df.with_columns(
...         c_struct=pl.col("c").arr.to_struct(["x", "y", "z"]),
...     )
... )
shape: (5, 2)
┌────────────────────┬──────────────────┐
│ c                  ┆ c_struct         │
│ ---                ┆ ---              │
│ array[i64, 3]      ┆ struct[3]        │
╞════════════════════╪══════════════════╡
│ [1, 0, 0]          ┆ {1,0,0}          │
│ [0, 1, 0]          ┆ {0,1,0}          │
│ [0, 0, 1]          ┆ {0,0,1}          │
│ [null, null, null] ┆ {null,null,null} │
│ null               ┆ null             │
└────────────────────┴──────────────────┘
>>> print(result["c_struct"].struct.unnest())
shape: (5, 3)
┌──────┬──────┬──────┐
│ x    ┆ y    ┆ z    │
│ ---  ┆ ---  ┆ ---  │
│ i64  ┆ i64  ┆ i64  │
╞══════╪══════╪══════╡
│ 1    ┆ 0    ┆ 0    │
│ 0    ┆ 1    ┆ 0    │
│ 0    ┆ 0    ┆ 1    │
│ null ┆ null ┆ null │
│ null ┆ null ┆ null │
└──────┴──────┴──────┘