pandas · difficulty ◆◆
pandas pivot() — reshape long rows into a report grid
pivot only moves values around — when two rows claim the same cell, it refuses to guess.
The one-liner that turns a long export into a monthly report grid, fails on duplicate rows, and whose obvious fix silently averages your revenue instead of adding it up.
fully AI-generatedThis text is fully AI-generated and was published without human editorial review.$ df.pivot()- 3
- pivot parameters
- 12
- pivot_table parameters
- 2.0.0
- Keyword-only since
- pandas 3.0.3
- Examples verified on
columns (required), index, values — all keyword-only in pandas 3.x
adds aggfunc, fill_value, margins, dropna, observed, sort and more; default aggfunc is 'mean'
changelog: 'Disallow passing non-keyword arguments to DataFrame.pivot' (GH 48301, April 2023)
every output block above was printed by this interpreter, not edited
What it does
`pivot(index=, columns=, values=)` reads three columns out of a long frame and lays them out on a two-dimensional grid: each unique `index` value becomes a row, each unique `columns` value becomes a column header, and the matching `values` entry fills the cell. That is the whole contract.
It performs no aggregation. Every cell has to be addressable by exactly one source row, so if two rows claim the same (index, column) pair you get `ValueError: Index contains duplicate entries, cannot reshape`. Pass a list to `values` and the result carries MultiIndex columns; pass a list to `index` or `columns` and that axis becomes nested. Leaving `index` out does not mean "no index" — it means "use the index the frame already has".
Why it matters
Databases hand you long format: one row per event, per city-month, per sensor reading. Reports, charts and feature matrices want wide format: one row per entity, one column per period. `pivot` is the bridge in that direction, `melt` is the bridge back.
In practice it is the difference between a `groupby` result you squint at and a table you can paste into a deck. Grouping gives you a long result with a MultiIndex; pivoting one of its columns gives you the report. Recognise the shape you need first — if the word "per" appears twice in the request, something is about to be pivoted, and if the word "total" appears, you probably want `pivot_table` instead.
Example
$ import pandas as pd
sales = pd.DataFrame({
"city": ["Wien", "Wien", "Graz", "Graz", "Linz", "Linz"],
"month": ["Jul", "Aug", "Jul", "Aug", "Jul", "Aug"],
"revenue": [41200, 39800, 18750, 21300, 9400, 11250],
})
report = sales.pivot(index="city", columns="month", values="revenue")
report["Total"] = report.sum(axis=1)
report.sort_values("Total", ascending=False)month Aug Jul Total
city
Wien 39800 41200 81000
Graz 21300 18750 40050
Linz 11250 9400 20650A long ERP-style export (one row per city-month) becomes the monthly report in one call. Every snippet here runs as printed once `import pandas as pd` is at the top. Note the dtypes: int64 stays int64 because every city has both months — the moment one pair is missing, this quietly turns into float.
$ orders = pd.DataFrame({
"store": ["Wien", "Wien", "Graz", "Graz"],
"quarter": ["Q1", "Q1", "Q1", "Q2"],
"total": [120.0, 80.0, 300.0, 210.0],
})
orders.pivot(index="store", columns="quarter", values="total")ValueError: Index contains duplicate entries, cannot reshapeTwo Wien rows land in the same cell, so pivot stops. There is no aggfunc to break the tie and it will not pick one for you. This is the exception that sends people to Stack Overflow, where the top answer tells them to switch to pivot_table — correctly, but without warning them about the default.
$ orders.pivot_table(index="store", columns="quarter", values="total",
aggfunc="sum", fill_value=0)quarter Q1 Q2
store
Graz 300.0 210.0
Wien 200.0 0.0The working fix: aggfunc="sum" for real totals, fill_value=0 so Wien's absent Q2 reads as zero rather than NaN. Both are pivot_table parameters — pivot takes neither. Drop aggfunc and Wien Q1 becomes 100.0, the mean of 120 and 80.
$ telemetry = pd.DataFrame({
"station": ["Wien-West", "Wien-West", "Graz-Süd", "Graz-Süd"],
"hour": [6, 7, 6, 7],
"temp_c": [11.4, 12.8, 9.1, 10.3],
"humidity": [78, 71, 83, 79],
})
wide = telemetry.pivot(index="station", columns="hour", values=["temp_c", "humidity"])
wide.columns = [f"{col}_{hr}h" for col, hr in wide.columns]
wide temp_c_6h temp_c_7h humidity_6h humidity_7h
station
Graz-Süd 9.1 10.3 83.0 79.0
Wien-West 11.4 12.8 78.0 71.0Two measures per station-hour gives MultiIndex columns — (temp_c, 6), (temp_c, 7), … — and the flat rename makes the frame writable to CSV without a two-row header. Worth noticing: humidity was int64 in the source and is float64 here, because the multi-value path packs both measures into one numpy block.
$ history = pd.DataFrame({
"city": ["Wien", "Wien", "Graz", "Graz"] * 2,
"year": [2025, 2025, 2025, 2025, 2026, 2026, 2026, 2026],
"quarter": ["Q1", "Q2", "Q1", "Q2"] * 2,
"revenue": [9800, 10450, 5100, 5600, 11200, 9900, 6100, 6400],
})
grid = history.pivot(index="city", columns=["year", "quarter"], values="revenue")
grid[2026]quarter Q1 Q2
city
Graz 6100 6400
Wien 11200 9900A list of keys gives nested header levels — year on top, quarter below. Selecting one level with grid[2026] returns an ordinary DataFrame, so you get a year-on-year comparison without a second reshape step or a filter.
Common flags
- columns=
- Required, keyword-only. The long column whose values become the new header row.
- index=
- Column(s) whose values become row labels. Omit it and the frame's existing index is used — usually a RangeIndex, which is rarely what you want.
- values=
- The column that supplies cell values. Omit it and every remaining column comes along, under a MultiIndex header.
- values=[a, b]
- List of measures → MultiIndex columns keyed (measure, column-value). Flatten before exporting.
- columns=['year', 'quarter']
- List of keys → nested header levels; grid[2026] then selects one level.
- df.pivot('a', 'b', 'c')
- Positional call: TypeError on pandas 3.x. The parameters have been keyword-only since 2.0.
History
Older than the calling convention
`pivot` predates pandas' stabilised API. The 0.4.3 source tree already carries it in `pandas/core/reshape.py` with the same three parameters it has today — `index`, `columns`, `values` — sitting next to `melt`. By 0.7.0 (February 9, 2012) the pair was documented as the long↔wide toolset.
The signature survived intact; how you call it did not. pandas 2.0.0 (April 3, 2023) disallowed non-keyword arguments (GH 48301), and 3.0.3 now answers `df.pivot("city", "month", "revenue")` with `TypeError: DataFrame.pivot() takes 1 positional argument but 4 were given`. Old blog posts and Stack Overflow answers still use the positional form — if a snippet throws that TypeError on a modern install, the code is old, not wrong.
Design note: pivot refuses to invent values
The split between `pivot` and `pivot_table` is deliberate. `pivot` is the low-level reshape with predictable behaviour; `pivot_table` is the Excel-compatible report builder, and it grew the reporting furniture: `aggfunc`, `fill_value`, `margins`, `dropna`, `observed`, `sort`. Twelve parameters in the current signature against `pivot`'s three.
What pandas did not do is let `pivot` aggregate with an implicit rule. Averaging two rows silently would be worse than failing, because a wrong revenue table looks exactly like a right one. The error message is blunt and the docs point at the fix, which is the right trade for a function whose only job is to move values around.
Under the hood
What unstack does with your dtypes
pivot builds a MultiIndex out of your index columns plus the column keys and hands it to `unstack` — the same engine behind stack/unstack. Two consequences fall out of that path.
First, unstack reindexes to the full product of row values × column keys, padding absent pairs with NaN. NaN only exists in float, so a single missing pair promotes the whole column: a month a city skipped comes back as `90.0`, not `90`. Second, when `values` is a list, pandas packs the chosen columns into one 2-D block (`data[values]._values`) before unstacking, so the measures have to share a dtype — humidity's int64 becomes float64 because temp_c is float64. An all-integer `values=[units, returns]` stays int64, which is the giveaway that this is block promotion rather than unstack. And because unstack sorts, your columns arrive alphabetically: August before July, Q1 before Q2 — reindex explicitly when month order matters.
Fun facts
Pros & cons
pros
- + Three parameters and no options to misconfigure: the reshape you ask for is the reshape you get.
- + Handles two levels of keys per axis in one call, so a year × quarter header needs no extra step.
- + Fails loudly on ambiguity instead of inventing an aggregation rule you did not ask for.
cons
- − No aggregation and no fill_value — duplicate pairs are an error, not a decision point.
- − Output columns are sorted by unstack, so month and quarter order has to be fixed with reindex.
- − Integer columns become floats as soon as one pair is missing, which quietly breaks dtype-sensitive joins downstream.
Takeaways
- 1pivot is layout, not arithmetic: if two rows collide on the same (index, column) pair, switch to pivot_table with an explicit aggfunc.
- 2Always pass index= explicitly — an omitted index means "the existing index", which is a RangeIndex far more often than you expect.
- 3Multi-measure pivots give MultiIndex columns; flatten with wide.columns = [f"{a}_{b}" for a, b in wide.columns] before writing CSV or JSON.
- 4Expect int → float on the first missing pair: unstack pads the full grid with NaN, and NaN only lives in float.
- 5Drill into a nested header level with plain indexing (grid[2026]) instead of rebuilding the pivot or filtering the long frame.
Related commands
archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →
