Tidy wide tables
Normalize repeated measurement columns for analysis or visualization.
Polars · Module
Reshapes a DataFrame from wide to long form, retaining optional identifier columns. Selected measured columns become rows represented by variable and value fields.
The method reshapes selected measured columns into two columns: one containing each source column name and one containing its corresponding value. Identifier columns remain attached to every generated row; when on is omitted, every column not listed in index is measured.
DataFrame.unpivot(on: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None, *, index: ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None = None, variable_name: str | None = None, value_name: str | None = None) -> DataFrame| Name | Type | Description |
|---|---|---|
on | ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None | Columns or selectors to use as value variables; if None, all columns not in index are used. |
index | ColumnNameOrSelector | Sequence[ColumnNameOrSelector] | None | Columns or selectors to use as identifier variables. |
variable_name | str | None | Name for the generated variable column; defaults to "variable". |
value_name | str | None | Name for the generated value column; defaults to "value". |
DataFrame
import polars as pl
frame = pl.DataFrame({
"city": ["Oslo", "Rome"],
"jan": [4, 12],
"feb": [5, 14],
})
long = frame.unpivot(
on=["jan", "feb"],
index="city",
variable_name="month",
value_name="temperature",
)
print(long)Converts the monthly measurement columns into rows while retaining the city identifier.
Normalize repeated measurement columns for analysis or visualization.
Convert a selected group of typed columns into a name-value representation.
Prepare a wide report for joins or grouped aggregation by measurement type.
unpivot changes a DataFrame from wide format to long format. The columns selected by on become values represented along the row axis, while index columns remain identifiers.
Follow-up: What happens when on is omitted? Every column not included in index is selected as a measured column.
on identifies the measured columns and index identifies the columns to preserve as identifiers. variable_name and value_name customize the two generated non-identifier columns, whose defaults are variable and value.
Follow-up: How would you reshape only numeric measurements while preserving a label? Pass a numeric selector for on and the label column as index.
The method returns a DataFrame with the identifier columns plus the variable and value columns. If on is an empty selection, no columns are used as measured variables.
Follow-up: How can the output be made predictable for downstream comparisons? Sort it after unpivoting, because row order is unspecified.
polars.DataFrame.pivotpolars.selectors.numericpandas.DataFrame.melt