Sub topic 13
Reshaping with pivot and unpivot
This chapter assumes you know pandas pivot_table and melt, and that you have read the earlier chapters on expressions and group by. It covers the Polars equivalents and the differences that cause errors when you port code.
Name mapping
| pandas | Polars | Notes |
|---|---|---|
| `pivot_table(index, columns, values, aggfunc)` | `DataFrame.pivot(on, index, values, aggregate_function)` | `columns` becomes `on`. |
| `melt(id_vars, value_vars, var_name, value_name)` | `DataFrame.unpivot(on, index, variable_name, value_name)` | `id_vars` becomes `index`. `value_vars` becomes `on`. |
Polars has no index, so the index argument only names the columns that identify each output row. The result is an ordinary frame, so you do not call reset_index().
Long to wide
import pandas as pd
import polars as pl
data = {
"region": ["East", "East", "West", "West", "West"],
"month": ["Jan", "Feb", "Jan", "Jan", "Feb"],
"revenue": [100, 150, 80, 20, 90],
}
# pandas
pdf = pd.DataFrame(data)
wide_pd = pdf.pivot_table(
index="region", columns="month", values="revenue", aggfunc="sum"
).reset_index()
# Polars
df = pl.DataFrame(data)
wide = df.pivot(
on="month", index="region", values="revenue", aggregate_function="sum"
)
print(wide)The West region has two January rows, so the sum is 100. Polars also returns the new columns in order of first appearance. pandas sorts them. Pass sort_columns=True to pivot if you need sorted columns.
Wide to long
long = wide.unpivot(
on=["Jan", "Feb"],
index="region",
variable_name="month",
value_name="revenue",
)
print(long)
# pandas equivalent
long_pd = wide_pd.melt(
id_vars="region",
value_vars=["Jan", "Feb"],
var_name="month",
value_name="revenue",
)If you leave out on, Polars unpivots every column that is not in index. You can also pass a selector or expression such as pl.exclude("region"), which helps when the month columns are not fixed.
Differences to check when porting
- Duplicates need an aggregation. pandas
pivotraises on duplicate keys, andpivot_tableaverages them by default. Polarspivotraises an error if several rows share anindexandonpair and you did not setaggregate_function. It does not default to the mean, so passaggregate_function="mean"to match pandas. - Missing combinations are null. If West had no February row, the cell would be null. pandas would give NaN, and
fill_valuewould replace it. In Polars, call.fill_null(0)after the pivot. - Pivot is eager only.
pivotexists onDataFramebut not onLazyFrame, because the output columns depend on the data values. In a lazy pipeline, callcollect()first, pivot, then call.lazy()again if you want to continue lazily.unpivotworks on both. - No MultiIndex columns. To pivot several value columns, pass a list to
values. Polars joins the names into flat column names instead of building a hierarchy.
Exercise
A pandas script calls df.pivot_table(index="id", columns="kind", values="amount") with no aggfunc. Which Polars call keeps the same results when some id and kind pairs appear more than once?
Show answer
df.pivot(on="kind", index="id", values="amount", aggregate_function="mean"). pandas pivot_table averages by default, and Polars errors on duplicates unless you give an aggregation. Any cells with no data are null instead of NaN.