Convert list-valued columns into one record per element.
Normalize nested records
Polars · Module
Expands List or Array values in selected DataFrame columns into separate rows, producing long-format data. It accepts names, expressions, selectors, and additional positional columns, with options for empty and null containers.
Call this method with one or more column names, expressions, or selectors whose values are lists or arrays. Polars expands each element into a separate row, retaining the other column values for the resulting rows; options control how empty and null containers are represented.
DataFrame.explode(columns, *more_columns, empty_as_null=False, keep_nulls=True)| Name | Type | Description |
|---|---|---|
columns | ColumnNameOrSelector | Iterable[ColumnNameOrSelector] | Column names, expressions, or a selector defining the columns to explode. The columns must use List or Array data types. |
more_columns | ColumnNameOrSelector | Additional columns to explode, supplied as positional arguments. |
empty_as_null | bool = False | Whether an empty list or array is converted into a null. |
keep_nulls | bool = True | Whether a null list or array is retained as a null value. |
DataFrame
import polars as pl
df = pl.DataFrame({
"group": ["a", "b"],
"values": [[1, 2], [3]],
})
result = df.explode("values")
print(result)Each list element becomes its own row while the group value is repeated.
Normalize nested records
Prepare relational analysis
Expand several aligned columns
It converts selected List or Array columns from nested values into long-format rows. Every element produces a row, and values in the other columns are carried along.
Follow-up: What input types are accepted? The selected columns must have List or Array data types; ordinary scalar columns cannot be exploded.
columns identifies the first column or collection of columns to expand, while additional columns can be supplied positionally through more_columns. Inputs may be column names, expressions, or selectors.
Follow-up: How would you select several columns without naming each one? Use a selector or an iterable of column names, expressions, or selectors.
empty_as_null controls empty List or Array values, and keep_nulls controls null List or Array values. Both default to False and True respectively.
Follow-up: What happens with an empty list under the defaults? It is exploded without converting the empty container to a null; enabling empty_as_null explicitly requests a null output.
polars.DataFrame.explodepolars.LazyFrame.explodepolars.Expr.explodepolars.Expr.arr.explode