Sub topic 4
Turning rows into columns with pivot
DataFrame.pivot reshapes a long table into a wide one. It takes the unique values of one column and makes them the row labels. It takes the unique values of another column and makes them the column labels. It then fills each cell from a third column. This chapter covers how that works, the options that control it, and the errors and surprises you will meet.
This chapter assumes you know basic Python, can create and index a DataFrame, and can select with [] and loc. It also assumes you have used groupby with aggregations such as sum. The previous chapters covered wide versus long layouts and melt. The code blocks below run in one session, and later blocks reuse names defined earlier.
What pivot does
Start with a long table that has one row per store and month:
import pandas as pd
long = pd.DataFrame({
"store": ["A", "B", "A", "B"],
"month": ["jan", "jan", "feb", "feb"],
"sales": [100, 80, 110, 90],
})
wide = long.pivot(index="store", columns="month", values="sales")
print(wide)month feb jan
store
A 110 100
B 90 80Three arguments drive the call:
| Argument | Role | In the example |
|---|---|---|
| `index` | Unique values become the row labels | `store` |
| `columns` | Unique values become the column labels | `month` |
| `values` | Supplies the number that goes in each cell | `sales` |
Each row of the input holds one (index, columns) pair and one value. pivot moves that value to the cell where the row label and column label meet.
In pandas 2.x, pivot accepts only keyword arguments. Write index=, columns= and values= every time. Calling long.pivot("store", "month", "sales") raises a TypeError.
The shape of the result
The result has some features that surprise people the first time.
- The column labels are sorted. The output shows
febbeforejan, althoughjancame first in the input.pivotsorts the unique values. For month names that is alphabetical order, not calendar order. - The index is named. The row labels carry the name
store, sostoreis no longer an ordinary column. - The column axis is named too. The name
monthsits above the columns. It is thecolumns.nameattribute, and it appears as the extra header line when you print.
To get a plain table back, reset the index and clear the axis name:
flat = wide.reset_index()
flat.columns.name = None
print(flat) store feb jan
0 A 110 100
1 B 90 80To control column order, select the columns in the order you want:
ordered = flat[["store", "jan", "feb"]]
print(ordered) store jan feb
0 A 100 110
1 B 80 90If you pivot often with calendar-based columns, you can convert the column to an ordered categorical before pivoting. For one-off work, selecting the columns by name is simpler and easier to read.
Several index or columns keys
index and columns each accept a list. The result then has a MultiIndex on that axis. A MultiIndex is an index with more than one level.
regional = pd.DataFrame({
"region": ["north", "north", "south", "south"],
"store": ["A", "B", "C", "D"],
"month": ["jan", "jan", "jan", "jan"],
"sales": [100, 80, 70, 60],
})
by_region = regional.pivot(
index=["region", "store"], columns="month", values="sales"
)
print(by_region)month jan
region store
north A 100
B 80
south C 70
D 60The row labels are now (region, store) pairs. reset_index() turns both levels back into ordinary columns. Multi-key index and columns lists need pandas 1.1 or later.
Pivoting more than one value column
If you leave out values, pivot uses every column that is not in index or columns. You can also pass a list. Either way, the columns gain an extra top level that names the original value column.
long["units"] = [10, 8, 11, 9]
both = long.pivot(index="store", columns="month", values=["sales", "units"])
print(both.columns.tolist())[('sales', 'feb'), ('sales', 'jan'), ('units', 'feb'), ('units', 'jan')]The columns are now tuples. You can select one block with both["sales"], or one cell column with both[("sales", "jan")]. A later chapter covers reading these labels and flattening them into plain names.
Using the existing index
If you leave out index, pivot uses the DataFrame's current index. This is handy when the row labels are already in place:
indexed = long.set_index("store")
print(indexed.pivot(columns="month", values="sales"))month feb jan
store
A 110 100
B 90 80Notice that store is not named in the call. It is the index, so it becomes the row labels without being listed.
Missing combinations become NaN
pivot builds a complete grid of every row label and column label. If a combination never appears in the input, its cell is empty and holds NaN.
gaps = pd.DataFrame({
"store": ["A", "A", "B"],
"month": ["jan", "feb", "jan"],
"sales": [100, 110, 80],
})
grid = gaps.pivot(index="store", columns="month", values="sales")
print(grid)
print(grid.dtypes.tolist())month feb jan
store
A 110.0 100.0
B NaN 80.0
[dtype('float64'), dtype('float64')]Store B has no February row, so that cell is NaN. Integer NumPy columns cannot hold NaN, so pandas converts the whole feb column to float64. The jan column also shows as float here because the pivot builds both columns together.
You have two ways to deal with this:
- Fill the gaps after the pivot with
grid.fillna(0). The columns stay float, so follow with.astype(int)if you need integers. - Convert to a nullable integer type with
grid.astype("Int64"). This keeps whole numbers and shows missing cells as<NA>.
The second option is better when a missing cell means "unknown" rather than "zero". A store with no February row may have had no sales, or its data may not have arrived.
When pivot refuses to run
pivot can only place one value in each cell. If the input has two rows with the same (index, columns) pair, it cannot choose between them and raises a ValueError:
dupes = pd.DataFrame({
"store": ["A", "A", "B"],
"month": ["jan", "jan", "jan"],
"sales": [60, 40, 80],
})
try:
dupes.pivot(index="store", columns="month", values="sales")
except ValueError as err:
print("pivot failed:", err)pivot failed: Index contains duplicate entries, cannot reshapeThis is a useful check. If your data should have one row per pair, the error tells you it does not. Before you reach for a fix, inspect the offending rows:
print(dupes[dupes.duplicated(["store", "month"], keep=False)]) store month sales
0 A jan 60
1 A jan 40Then choose deliberately. If the duplicates are a data-entry mistake, clean them. If they are legitimate repeated measurements, you need to aggregate them, which is the job of pivot_table in an upcoming chapter.
Common mistakes
- Passing positional arguments. In pandas 2.x this raises a
TypeError. Use keywords. - Expecting an ordinary index. After
pivot, the row key is the index. Callingwide["store"]raises aKeyError. Usereset_index()first. - Forgetting the axis name. The leftover
monthheader appears when you print or export. Setcolumns.name = Noneor userename_axis(columns=None). - Assuming input order is kept. Row and column labels are sorted, not kept in first-seen order.
- Ignoring dtype changes. A single missing cell turns an integer column into floats.
- Leaving extra columns in play. When you omit
values, every other column is pivoted. A stray text column can give you a much wider table than you intended. Namevaluesexplicitly.
Choosing pivot
Use pivot when each (index, columns) pair appears at most once and you only need to rearrange the data. It does no arithmetic, so it never changes a value. Use it also as a check on your data, since it fails loudly on duplicates. When the pairs repeat and you need to combine them, use pivot_table or groupby followed by unstack.
Exercise
The DataFrame df has columns student, subject and score, with one row per student and subject pair. Write the call that gives one row per student and one column per subject. Then say what happens to a student who has no row for a subject, and what happens to the dtype of that subject's column.
Show answer
Use df.pivot(index="student", columns="subject", values="score"). A student with no row for a subject gets NaN in that cell. Because NaN cannot be stored in an integer NumPy column, pandas stores that subject's column as float64. To keep whole numbers, call .astype("Int64") on the result, which shows the missing cell as <NA>. Add .reset_index() if you want student as an ordinary column.
Exercise
This call raises ValueError: Index contains duplicate entries, cannot reshape: df.pivot(index="store", columns="month", values="sales"). What does the error mean, and how can you find the cause with a single expression?
Show answer
At least one (store, month) pair appears in more than one row, so pivot has no rule to pick one value for that cell. Show the offending rows with df[df.duplicated(["store", "month"], keep=False)]. The keep=False argument marks every row in a duplicate group, not just the later ones. Then either remove the bad rows or aggregate them with pivot_table.