pivot
df.pivot(index="id", columns="key", values="value") reshapes long data into wide: one row per index value and one column per distinct key. Each index/key pair must appear once; if there are duplicates, use pivot_table, which aggregates them.
Syntax
df.pivot(index=None, columns=None, values=None)| Part | What it is |
|---|---|
index | Column whose values become the row labels |
columns | Column whose distinct values become the new column names |
values | Column(s) that fill the cells; omit to spread all remaining columns |
Examples
import pandas as pd
long = pd.DataFrame({"date": ["2024-01", "2024-01", "2024-02", "2024-02"],
"city": ["Oslo", "Rome", "Oslo", "Rome"],
"temp": [-3, 8, -1, 10]})
long.pivot(index="date", columns="city", values="temp")Result: city Oslo Rome date 2024-01 -3 8 2024-02 -1 10
wide = long.pivot(index="date", columns="city", values="temp")
wide.reset_index().rename_axis(columns=None)Result: date Oslo Rome 0 2024-01 -3 8 1 2024-02 -1 10
reset_index turns date back into a column; rename_axis(columns=None) removes the city label above the header.
long.set_index(["date", "city"])["temp"].unstack()Result: city Oslo Rome date 2024-01 -3 8 2024-02 -1 10
unstack on a two-level index does the same job as pivot.
Common mistakes
- ValueError: Index contains duplicate entries, cannot reshape: a date/city pair occurs more than once; use pivot_table with an aggfunc, or drop the duplicates first.
- The result has a two-level column header: you omitted values with several remaining columns; pass values="temp".
- KeyError: you passed positional arguments in the old order; use the keyword names index=, columns=, values=.
Practice pivot
These drills check your answer on live data, free, no account needed.
- Long to wide with pivotReshape `long` into a table with one row per store and one column per quarter, holding the sales values.
- Index level into columns with unstack`s` holds revenue indexed by region and quarter. Use `unstack` so regions are rows and quarters are columns. Missing combinations stay NaN.
Questions
pivot or pivot_table?
pivot when each row/column pair is unique and you only want to reshape. pivot_table when you need to aggregate (sum, mean) or when duplicates may exist.
How do I pivot without an index column?
Leave index=None and pandas uses the existing index; usually you want to reset_index first so the row labels are meaningful.
Related
- pivot_tableHow to build a pivot table in pandas with pivot_table: index, columns, values, aggfunc, fill_value for empty cells, margins for totals, several aggregations.
- meltHow to use melt in pandas to turn wide data (one column per month or category) into long format with a variable and a value column, keeping id columns.
- set_index and reset_indexHow to use set_index and reset_index in pandas: make a column the row index, go back to a plain column, drop the index, and flatten a groupby result.
- groupbyHow groupby works in pandas: group by one or more columns, apply sum, mean, count or size, get a flat table with as_index=False, and iterate over groups.