Sub topic 12
Reshaping with pivot and unpivot
This chapter assumes you know how to build a DataFrame, call select and group_by, and read a schema. It covers how to switch a table between long and wide layouts.
Long and wide layouts
A long table has one row per observation, with a column naming the category. A wide table spreads categories across columns. Long data suits grouping and filtering. Wide data suits reports and side-by-side comparison.
Pivot: long to wide
DataFrame.pivot takes three main arguments:
on: the column whose values become new column names.index: the column or columns that identify each output row.values: the column that fills the cells.
import polars as pl
long_df = pl.DataFrame(
{
"region": ["north", "north", "south", "south"],
"quarter": ["Q1", "Q2", "Q1", "Q2"],
"amount": [10, 20, 30, 40],
}
)
wide = long_df.pivot(on="quarter", index="region", values="amount")
print(wide)The result has the columns region, Q1 and Q2. There is one row for each region.
Handling duplicates
Each index and on combination must be unique unless you say how to combine rows. If two rows share the same region and quarter, Polars raises an error instead of guessing. Pass aggregate_function to resolve this.
dup = pl.DataFrame(
{
"region": ["north", "north", "north", "south"],
"quarter": ["Q1", "Q1", "Q2", "Q1"],
"amount": [10, 5, 20, 30],
}
)
print(
dup.pivot(
on="quarter",
index="region",
values="amount",
aggregate_function="sum",
)
)North and Q1 now holds 15. A combination with no rows, such as south and Q2, becomes null. Handle those cells with fill_null if you need a default.
Unpivot: wide to long
DataFrame.unpivot reverses the operation:
onlists the columns to turn into rows.indexlists the columns to keep as identifiers.variable_nameandvalue_namename the two new columns.
back = wide.unpivot(
on=["Q1", "Q2"],
index="region",
variable_name="quarter",
value_name="amount",
)
print(back.sort("region", "quarter"))The output matches the original long table. Sorting makes the row order predictable, since unpivot emits all rows for the first column before moving to the next.
Common errors
- Duplicate entries. The pivot fails when index and
onpairs repeat. Addaggregate_functionor aggregate first withgroup_by. - Lazy frames.
pivotexists only onDataFrame, because Polars cannot know the output columns before it reads the data. Callcollect()first.unpivotworks on both eager and lazy frames. - Mixed dtypes in
unpivot. The columns you unpivot should share a type, or the value column must be able to hold them. Cast them first withpl.col(...).cast(...)if needed. - Column order. Pivoted columns appear in the order their values first occur in the data. Select them explicitly if the order matters.
Exercise
A DataFrame has the columns store, month and units. Some store and month pairs appear twice. Write the pivot call that gives one row per store, one column per month, and the total units in each cell.
Show answer
df.pivot(on="month", index="store", values="units", aggregatefunction="sum"). Without aggregatefunction, the duplicate store and month pairs would raise an error.
Exercise
Why can you not call pivot on a LazyFrame?
Show answer
The output columns depend on the distinct values in the on column, which Polars only knows after reading the data. The lazy engine needs the schema before it runs, so call collect() first and then pivot.