Sub topic 13
Reshaping with pivot and unpivot
This chapter assumes you know pandas pivot_table, melt, and stack/unstack. It also assumes you have read the earlier chapters on expressions and group by. Here you will translate those reshaping calls to Polars pivot and unpivot. You will also learn where the two libraries differ in defaults and naming.
Long and wide tables
A long table has one row per observation, with a column that says what was measured. A wide table spreads those categories across separate columns. Pivoting goes from long to wide. Unpivoting goes from wide to long.
The pandas to Polars mapping
| pandas | Polars | Notes |
|---|---|---|
| `df.pivot_table(index=, columns=, values=, aggfunc=)` | `df.pivot(on=, index=, values=, aggregate_function=)` | `columns` becomes `on`. |
| `df.pivot(...)` | `df.pivot(...)` with no aggregation | Duplicate keys raise an error in both libraries. |
| `df.melt(id_vars=, value_vars=, var_name=, value_name=)` | `df.unpivot(index=, on=, variable_name=, value_name=)` | `id_vars` becomes `index`. `value_vars` becomes `on`. |
| `stack` / `unstack` | `unpivot` / `pivot` | Polars has no MultiIndex, so it has no direct equivalent. |
Older Polars code may use melt. It was renamed to unpivot in Polars 1.0, and the old columns argument of pivot became on at the same time.
Pivot: long to wide
This example builds a long table and pivots it.
import polars as pl
sales = pl.DataFrame(
{
"region": ["north", "north", "south", "south", "north"],
"quarter": ["Q1", "Q2", "Q1", "Q2", "Q1"],
"revenue": [100, 150, 80, 120, 20],
}
)
wide = sales.pivot(
on="quarter",
index="region",
values="revenue",
aggregate_function="sum",
)
print(wide)The result has three columns: region, Q1 and Q2. The north region has two Q1 rows, 100 and 20, and sum combines them into 120. The region column is an ordinary column. Polars has no index, so there is nothing to reset_index().
The pandas version of the same operation looks like this:
import pandas as pd
sales_pd = pd.DataFrame(
{
"region": ["north", "north", "south", "south", "north"],
"quarter": ["Q1", "Q2", "Q1", "Q2", "Q1"],
"revenue": [100, 150, 80, 120, 20],
}
)
wide_pd = sales_pd.pivot_table(
index="region", columns="quarter", values="revenue", aggfunc="sum"
).reset_index()Defaults that differ from pandas
- Aggregation is explicit.
pivot_tabledefaults toaggfunc="mean". Polarspivotdefaults to no aggregation. If anyindex/onpair occurs more than once, Polars raises an error instead of silently averaging. Always passaggregate_functionwhen your data can contain duplicates. - Column order follows first appearance. pandas sorts the new columns. Polars keeps them in the order the values first appear in the data. Pass
sort_columns=Truefor sorted output. - Missing combinations become null. pandas gives
NaN. Polars givesnull, which is the missing-value marker covered in the null versus NaN chapter. Usefill_null(0)if you want zeros. - No margins.
pivot_table(margins=True)has no counterpart. Compute totals with a separategroup_byor withover.
The aggregation can be a string such as "sum", "mean", "min", "max", "first", "last", "median" or "len". It can also be an expression, which is useful for custom logic:
filled = sales.pivot(
on="quarter",
index="region",
values="revenue",
aggregate_function=pl.element().sum(),
sort_columns=True,
).fill_null(0)Inside pivot, pl.element() refers to the group of values that fall in each output cell.
Several values or several index columns
Pass a list to index to keep more than one identifying column. Pass a list to values to pivot several measures at once. With several value columns, Polars prefixes each new column with the value column name, for example revenue_Q1 and units_Q1. This replaces the MultiIndex columns that pandas produces.
Avoid a list for on unless you need it. Polars combines the values into a single generated column name, which is awkward to refer to later. A cleaner approach is to build one key column first with pl.concat_str, then pivot on that column.
Unpivot: wide to long
unpivot is the inverse. The index columns stay as identifiers, and the on columns are stacked into two new columns.
import polars as pl
wide = pl.DataFrame(
{
"region": ["north", "south"],
"Q1": [120, 80],
"Q2": [150, 120],
}
)
long = wide.unpivot(
on=["Q1", "Q2"],
index="region",
variable_name="quarter",
value_name="revenue",
)
print(long)The output has four rows. The Q1 values come first, then the Q2 values, which matches the order melt produces. If you omit on, Polars unpivots every column that is not in index. If you omit the names, the new columns are called variable and value.
Selectors save you from typing column lists. They are useful when new quarters appear over time:
import polars as pl
import polars.selectors as cs
wide = pl.DataFrame(
{"region": ["north", "south"], "Q1": [120, 80], "Q2": [150, 120]}
)
long = wide.unpivot(
on=cs.starts_with("Q"),
index="region",
variable_name="quarter",
value_name="revenue",
)The on columns end up in a single value column, so they need a common dtype. Cast them yourself before unpivoting if they differ, for example pl.col("Q1", "Q2").cast(pl.Float64). An explicit cast is clearer than relying on automatic type promotion.
Pivot and the lazy API
pivot exists only on DataFrame, not on LazyFrame. The reason is that Polars cannot know the output columns until it has seen the data. To use it in a lazy pipeline, collect first, pivot, and return to lazy mode if needed:
import polars as pl
wide = (
pl.LazyFrame(
{"region": ["n", "s", "n"], "quarter": ["Q1", "Q1", "Q2"], "revenue": [1, 2, 3]}
)
.filter(pl.col("revenue") > 0)
.collect()
.pivot(on="quarter", index="region", values="revenue", aggregate_function="sum")
.lazy()
)unpivot works on both DataFrame and LazyFrame, because its output schema is known in advance.
Common errors
- Duplicate entries error. You called
pivotwithoutaggregate_functionon data with repeated keys. Add an aggregation, or deduplicate first. - Unexpected column order. Compare against pandas with
sort_columns=True, or reorder explicitly withselect. NaNexpected,nullfound. Check for nulls withis_null(), notis_nan().- Name not found after pivot. The new column names come from data values, so they are strings. A numeric
oncolumn such as year produces columns named"2024". Select them withpl.col("2024").
Exercise
A pandas call is df.pivot_table(index="store", columns="month", values="sales") and returns average sales per store and month. Write the Polars equivalent, and state two differences you must handle for the output to match.
Show answer
df.pivot(on="month", index="store", values="sales", aggregate_function="mean"). The aggregation must be passed explicitly, because pandas defaults to mean while Polars defaults to none and errors on duplicate keys. Also, Polars keeps columns in order of first appearance, so add sort_columns=True to match pandas ordering, and store is a regular column rather than an index.
Exercise
You have a wide table with columns id, jan, feb, mar. Write a Polars call that returns a long table with columns id, month, sales.
Show answer
df.unpivot(on=["jan", "feb", "mar"], index="id", variable_name="month", value_name="sales"). You can replace the list with cs.by_name("jan", "feb", "mar") or omit on entirely, since all non-index columns are unpivoted by default.