Create a struct column
Group related values into one nested column while retaining named fields.
Polars · Function
Collects columns or expressions into a single struct column. It returns an expression by default or an evaluated Series when eager=True.
pl.struct collects columns or expressions into a single struct-valued expression. Positional inputs become fields using their column names, keyword inputs use the keyword as the field name, and eager=True evaluates immediately to a Series.
polars.struct(exprs: IntoExpr | Iterable[IntoExpr]*, schema: SchemaDict | None = None, eager: bool = False, **named_exprs: IntoExpr) → Expr | Series| Name | Type | Description |
|---|---|---|
exprs | IntoExpr | Iterable[IntoExpr] | Column or columns to collect into a struct; strings are column names and other non-expressions are literals. |
schema | SchemaDict | None | Optional mapping that explicitly defines struct field data types; its keys define columns when no expressions are supplied. |
eager | bool | If true, evaluate immediately and return a Series; otherwise return an expression. |
named_exprs | IntoExpr | Additional columns or expressions to collect; each field is renamed to its keyword. |
Expr | Series
import polars as pl
df = pl.DataFrame({"a": [1, 2], "b": ["x", "y"]})
result = df.select(
pl.struct("a", b="b").alias("record")
)
print(result)Packs columns into one struct column, naming the fields a and b.
Group related values into one nested column while retaining named fields.
Build a multi-column expression that can be processed as one value.
Give packed fields stable names independent of their source columns.
pl.struct packs multiple columns or expressions into one struct column. With the default eager=False, it returns an Expr that can participate in a lazy or DataFrame expression pipeline.
Follow-up: How would you obtain an immediate result? Set eager=True, which evaluates the inputs and returns a Series instead of an expression.
Positional inputs are collected as struct fields, and strings are interpreted as column names. Keyword expressions add fields whose names are the supplied keywords.
Follow-up: How can field names differ from source column names? Pass an input as a keyword expression, such as pl.struct(label="source").
schema optionally specifies the struct field data types. When no columns or expressions are supplied, its keys can also define the columns.
Follow-up: When is an explicit schema useful? Use it when field dtypes must be declared rather than inferred from supplied expressions.
polars.Expr.struct.fieldpolars.Expr.struct.with_fieldspolars.datatypes.StructDataFrame.unnest