Sub topic 12
Reshaping with pivot and unpivot
This chapter covers moving data between long and wide layouts with DataFrame.pivot and DataFrame.unpivot. It assumes you know how to build a DataFrame, how group_by and agg work, and what a null is in Polars. Examples use Polars 1.x, where pivot takes on= and unpivot replaced the older melt.
Long and wide layouts
The same facts can be stored in two shapes.
- Long format has one row per observation. Each row carries a key, a label and a value.
- Wide format has one row per entity. Each label becomes its own column.
Long data suits grouping, filtering and joining, because every measurement lives in the same column. Wide data suits reports and spreadsheets, where you want to compare labels side by side. pivot goes from long to wide. unpivot goes from wide to long.
Pivoting long data to wide
Start with quarterly sales in long format. East has no Q4 row and west has no Q3 row.
import polars as pl
long = pl.DataFrame(
{
"region": ["east", "east", "east", "west", "west", "west"],
"quarter": ["Q1", "Q2", "Q3", "Q1", "Q2", "Q4"],
"amount": [100, 120, 90, 80, 95, 110],
}
)
wide = long.pivot(on="quarter", index="region", values="amount")
print(wide)pivot takes three main arguments.
| Argument | Role | In this example |
|---|---|---|
| `on` | The column whose unique values become new column names | `quarter` |
| `index` | The column or columns that identify one output row | `region` |
| `values` | The column whose numbers fill the new cells | `amount` |
The result has one row per region and one column per quarter.
| region | Q1 | Q2 | Q3 | Q4 |
|---|---|---|---|---|
| east | 100 | 120 | 90 | null |
| west | 80 | 95 | null | 110 |
Combinations that do not exist in the input become null. A null here means "no row existed", which is different from a recorded zero. Decide deliberately whether to keep the nulls or fill them, as the next section shows.
Output columns appear in order of first appearance in the on column. Do not rely on that order for later code. Select columns by name instead.
Filling the gaps
Treat missing quarters as zero sales only if that matches the business meaning. If it does, fill after pivoting.
filled = wide.with_columns(pl.exclude("region").fill_null(0))
print(filled)pl.exclude("region") selects every column except region, so the fill applies to all quarter columns without listing them.
Duplicate keys need an aggregation
pivot has to put exactly one value in each cell. If two input rows share the same index and on values, Polars cannot choose between them, and it raises an error. Add a second east Q1 row to see this.
dup = pl.concat(
[
long,
pl.DataFrame({"region": ["east"], "quarter": ["Q1"], "amount": [20]}),
]
)
try:
dup.pivot(on="quarter", index="region", values="amount")
except Exception as e:
print(type(e).__name__)
totals = dup.pivot(
on="quarter",
index="region",
values="amount",
aggregate_function="sum",
)
print(totals)With aggregate_function="sum", the east Q1 cell becomes 120. The string options include "sum", "mean", "median", "min", "max", "first", "last" and "len". You can also pass an expression such as pl.element().sum().
Several index and value columns
index and values each accept a list. Use a list for index when a row is identified by more than one column, such as region and year. Use a list for values when you want several measures spread across the same label columns. In that case the output column names combine the value column name and the on label, so check df.columns before you write code that refers to them.
The on argument can also be a list. Each unique combination of labels then gets its own column. This is useful, but it can multiply the column count quickly, so check n_unique on the on columns first.
Unpivoting wide data to long
unpivot reverses the operation. You choose which columns hold identifying information (index) and which columns to melt into rows (on).
back = wide.unpivot(
on=["Q1", "Q2", "Q3", "Q4"],
index="region",
variable_name="quarter",
value_name="amount",
)
print(back)The output has two new columns. variable_name holds the old column names, and value_name holds the cell values. If you omit those arguments, the columns are called variable and value.
| region | quarter | amount |
|---|---|---|
| east | Q1 | 100 |
| west | Q1 | 80 |
| east | Q2 | 120 |
| west | Q2 | 95 |
| east | Q3 | 90 |
| west | Q3 | null |
| east | Q4 | null |
| west | Q4 | 110 |
The rows come out column by column, so all Q1 rows come first. Sort afterwards if you need another order. The nulls from the pivot come back as null rows, so the round trip is not exactly lossless. Drop them to recover the original six rows.
restored = back.drop_nulls("amount").sort("region", "quarter")
print(restored)Choosing columns with selectors
Typing every column name is brittle. on accepts selectors, which choose columns by pattern or by dtype.
import polars.selectors as cs
back2 = wide.unpivot(cs.starts_with("Q"), index="region")
print(back2.columns)This prints ['region', 'variable', 'value']. If a Q5 column appears later, the code picks it up without changes.
Pivot is eager only
pivot exists on DataFrame but not on LazyFrame. The output columns depend on the data, because the set of unique values in on is not known until the data is read. A lazy plan needs the output schema in advance. unpivot has no such problem, so it works on both. If you are in a lazy pipeline, you have two options.
- Call
collect()before the pivot, then continue eagerly. - Build the wide columns yourself with
group_byand filtered aggregations, when you know the labels up front.
labels = ["Q1", "Q2", "Q3", "Q4"]
lazy_wide = (
long.lazy()
.group_by("region")
.agg(
[
pl.col("amount").filter(pl.col("quarter") == q).sum().alias(q)
for q in labels
]
)
.sort("region")
.collect()
)
print(lazy_wide)This stays lazy until collect(). There is one behavioral difference. Summing zero rows gives 0, not null, so east Q4 is 0 here. Use .first() instead of .sum() if you want to keep nulls for missing cells and each combination occurs at most once.
Common errors
- Duplicate keys with no aggregation. The error means the
indexandoncolumns do not uniquely identify a row. Fix the data or passaggregate_function. - Old argument names. Code using
columns=inpivotor themeltmethod comes from Polars before 1.0. Useon=andunpivot. - Spaces or mixed types in labels. Pivot turns label values into column names. Labels that are not strings are converted, and messy text gives messy column names. Clean them with string expressions first.
- Pivoting on a high-cardinality column. A column with thousands of unique values makes thousands of columns. That is rarely what you want. Group and aggregate instead.
- Assuming column order. Select the output columns by name.
When to reshape
Keep data long while you compute. Grouping, joining and filtering are all simpler on long data, and one group_by can handle every label at once. Pivot at the end, when you present results or hand them to a tool that expects columns. Unpivot at the start when you receive a wide export and need to analyze it.
Exercise
A DataFrame sales has columns store, month and revenue. The pair (store, month) can appear more than once because of late corrections. Write a call that produces one row per store with one column per month, where corrections are added to the original figure. Then say what happens to a store that has no rows for a given month.
Show answer
Use sales.pivot(on="month", index="store", values="revenue", aggregate_function="sum"). The sum adds corrections to the original figure for each store and month. A store with no rows for a month gets null in that month's column, because no input row existed for the combination. Call .fill_null(0) on the month columns afterwards only if a missing month should count as zero revenue.