polars.Series.list.to_struct#
- Series.list.to_struct(fields: Sequence[str]) Series[source]#
Convert the series of type
Listto a series of typeStruct.- Parameters:
- fields
Field names to use for the output. The number of names determines how many fields will be in the output.
Examples
>>> s = pl.Series( ... [ ... [1], ... [0, 1], ... [1, 0, 1], ... [], ... [None, 1], ... None, ... ], ... ) >>> print(result := s.list.to_struct(["x", "y"])) shape: (6,) Series: '' [struct[2]] [ {1,null} {0,1} {1,0} {null,null} {null,1} null ] >>> print(result.struct.unnest()) shape: (6, 2) ┌──────┬──────┐ │ x ┆ y │ │ --- ┆ --- │ │ i64 ┆ i64 │ ╞══════╪══════╡ │ 1 ┆ null │ │ 0 ┆ 1 │ │ 1 ┆ 0 │ │ null ┆ null │ │ null ┆ 1 │ │ null ┆ null │ └──────┴──────┘
Unnest to a struct with a number of fields matching the length of the longest list:
>>> print( ... result := s.list.to_struct( ... [f"field_{i}" for i in range(s.list.len().max() or 0)] ... ) ... ) shape: (6,) Series: '' [struct[3]] [ {1,null,null} {0,1,null} {1,0,1} {null,null,null} {null,1,null} null ] >>> print(result.struct.unnest()) shape: (6, 3) ┌─────────┬─────────┬─────────┐ │ field_0 ┆ field_1 ┆ field_2 │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ i64 │ ╞═════════╪═════════╪═════════╡ │ 1 ┆ null ┆ null │ │ 0 ┆ 1 ┆ null │ │ 1 ┆ 0 ┆ 1 │ │ null ┆ null ┆ null │ │ null ┆ 1 ┆ null │ │ null ┆ null ┆ null │ └─────────┴─────────┴─────────┘