polars.Series.arr.to_struct#

Series.arr.to_struct(fields: Sequence[str] | None = None) → Series[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

>>> s = pl.Series(
...     [
...         [1, 0, 0],
...         [0, 1, 0],
...         [0, 0, 1],
...         [None, None, None],
...         None,
...     ],
...     dtype=pl.Array(pl.Int64, 3),
... )
>>> print(result := s.arr.to_struct())
shape: (5,)
Series: '' [struct[3]]
[
        {1,0,0}
        {0,1,0}
        {0,0,1}
        {null,null,null}
        null
]
>>> print(result.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 := s.arr.to_struct(["x", "y", "z"]))
shape: (5,)
Series: '' [struct[3]]
[
        {1,0,0}
        {0,1,0}
        {0,0,1}
        {null,null,null}
        null
]
>>> print(result.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 │
└──────┴──────┴──────┘