Sub topic 4
Turning rows into columns with pivot
This chapter assumes you can build a DataFrame, select columns, and have used melt to go from wide to long. Here you go the other way: pivot takes values stored in rows and spreads them across new columns.
The idea
A long table has one row per observation. A wide table has one row per entity, with one column per category. pivot needs three answers:
index: which column becomes the row labels.columns: which column's values become the new column names.values: which column fills the cells.
A worked example
Start from the long table produced by melt.
import pandas as pd
wide = pd.DataFrame({
"store": ["A", "B"],
"jan": [100, 80],
"feb": [110, 90],
})
long = wide.melt(id_vars="store", var_name="month", value_name="sales")
print(long)
back = long.pivot(index="store", columns="month", values="sales")
back = back.reset_index()
back.columns.name = None
print(back)The first print shows four rows: store A and B, each with a jan and a feb row. The second print shows two rows again. The month columns appear in sorted order, feb before jan, not in the order of the original table.
The two cleanup lines
pivot returns a DataFrame whose index is store and whose columns carry the name month. Two lines make it look like an ordinary table:
reset_index()movesstorefrom the index back to a normal column.back.columns.name = Noneremoves the leftovermonthlabel that sits above the column names.
Neither line changes the data. Both only tidy the labels.
When pivot fails
pivot only reshapes. It never combines values. If two rows share the same index and columns pair, it cannot decide which value belongs in that cell.
import pandas as pd
sales = pd.DataFrame({
"store": ["A", "A", "B", "B"],
"month": ["jan", "jan", "jan", "feb"],
"sales": [60, 40, 80, 90],
})
try:
sales.pivot(index="store", columns="month", values="sales")
except ValueError as err:
print("pivot failed:", err)Store A has two jan rows, so the call raises a ValueError about duplicate entries. The message is the symptom. The cause is that the pair (A, jan) is not unique.
Checking before you pivot
Test for duplicate keys before calling pivot. This costs one line and gives a clearer message than the error does.
dupes = sales.duplicated(subset=["store", "month"], keep=False)
print(sales[dupes])The output lists every row involved in a clash, so you can decide whether to fix the source data or aggregate.
Missing cells
When a pair is absent, pivot does not fail. It fills the cell with NaN. In the table above, store A has no feb row, so its feb cell would be NaN once duplicates are resolved. A column containing NaN becomes floating point, so integer sales may turn into 100.0.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Duplicate `index`/`columns` pairs | `ValueError` | Aggregate with `pivot_table` |
| Forgetting `reset_index()` | `store` is hidden in the index | Call `reset_index()` |
| Expecting original column order | Columns are sorted | Reorder with `back[["jan", "feb"]]` |
| Leaving `columns.name` set | Stray `month` label over the columns | Set it to `None` |
Exercise
A DataFrame has columns city, year and rainfall. The pair (Oslo, 2024) appears twice. You call df.pivot(index="city", columns="year", values="rainfall"). What happens, and what is one correct way to get a wide table?
Show answer
pivot raises a ValueError because (Oslo, 2024) is not a unique pair, so it cannot choose one rainfall value for that cell. Use df.pivot_table(index="city", columns="year", values="rainfall", aggfunc="mean") (or "sum") to combine the duplicate rows into one value.
Exercise
After pivoting, your table has store as the row labels and the text "month" printed above the column names. Which two statements give you a plain table with store as a normal column and no "month" label?
Show answer
result = result.reset_index() moves store into a normal column, and result.columns.name = None removes the "month" label.