Sub topic 16
Reshaping with pivot_table and melt
This chapter assumes you can select rows and columns with loc, build a groupby summary, and read a DataFrame that has a MultiIndex only at a basic level. Reshaping changes how a table is laid out without changing the facts in it. You will move between two layouts:
- Long format: one row per observation. Each variable has its own column.
- Wide format: one row per entity, with one column per category of some variable, such as one column per year.
pivot_table goes from long to wide and summarizes along the way. melt goes from wide to long.
The sample data
The examples below share one session. The data is long format, with one row per city and year. Lima has no 2024 row, which will matter later.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Oslo", "Rome", "Rome", "Lima", "Pune", "Pune"],
"region": ["EU", "EU", "EU", "EU", "SA", "AS", "AS"],
"year": [2023, 2024, 2023, 2024, 2023, 2023, 2024],
"pop_k": [700, 710, 2800, 2850, 10700, 3100, 3200],
})
print(df)pivot_table: long to wide with aggregation
pivot_table takes four main arguments:
index: the column whose values become the row labels.columns: the column whose values become the column labels.values: the column to summarize.aggfunc: how to combine values that land in the same cell.
wide = df.pivot_table(
index="region", columns="year", values="pop_k", aggfunc="sum"
)
print(wide)The result has one row per region and one column per year. The column Index is named year, and the row Index is named region. EU in 2023 is 3500, which is Oslo's 700 plus Rome's 2800.
Two details matter here:
aggfuncdefaults to"mean". If you leave it out, cells that combine several rows are averaged, not summed. This is a common source of wrong totals.- No row exists for Lima in 2024, so the cell for SA in 2024 is
NaN. This is the same missing-data behavior covered in earlier chapters, and it turns that column's dtype into float.
Filling and totals
fill_value replaces empty cells in the result. margins=True adds a row and a column of totals, labeled All by default.
wide_totals = df.pivot_table(
index="region", columns="year", values="pop_k",
aggfunc="sum", fill_value=0, margins=True,
)
print(wide_totals)| region | 2023 | 2024 | All |
|---|---|---|---|
| AS | 3100 | 3200 | 6300 |
| EU | 3500 | 3560 | 7060 |
| SA | 10700 | 0 | 10700 |
| All | 17300 | 6760 | 24060 |
Here fill_value=0 is a reporting choice. It says "no rows means zero people counted". For a measurement such as an average, a zero would be misleading, so leave the NaN in place.
Several aggregations and flat column names
Passing a list to aggfunc creates a MultiIndex on the columns, with the function name on the first level and the value column on the second. Flatten it before you save or merge the result.
stats = df.pivot_table(index="region", values="pop_k", aggfunc=["sum", "count"])
stats.columns = ["_".join(map(str, c)) for c in stats.columns.to_flat_index()]
stats = stats.reset_index()
print(stats.columns.tolist()) # ['region', 'sum_pop_k', 'count_pop_k']reset_index() turns the row labels back into an ordinary column. Most downstream steps, such as merge and melt, are easier with a plain integer index.
pivot versus pivot_table
DataFrame.pivot also reshapes long to wide, but it does no aggregation. If any combination of index and column values appears more than once, it raises a ValueError.
try:
df.pivot(index="region", columns="year", values="pop_k")
except ValueError as err:
print("pivot failed:", type(err).__name__)This fails because EU in 2023 appears twice, once for Oslo and once for Rome. Use pivot when each combination is guaranteed unique and you want an error if that guarantee breaks. Use pivot_table when duplicates are expected and should be combined.
melt: wide to long
melt is the inverse operation. It takes several columns and stacks them into two: one that holds the old column labels, and one that holds the values. Its main arguments are:
id_vars: columns to keep as they are, one per output row.value_vars: columns to stack. If you omit it, every column not inid_varsis stacked.var_name: the name for the column that holds the old labels.value_name: the name for the column that holds the values.
wide has region as its row index, so call reset_index first. Otherwise region is not a column that melt can see.
long = (
wide.reset_index()
.melt(id_vars="region", var_name="year", value_name="pop_k")
)
print(long)The output has six rows: three regions times two years. The SA row for 2024 is kept with a NaN value, because melt does not drop missing entries. Add .dropna(subset=["pop_k"]) if you want only observed values.
A round trip is not always lossless
Reshaping df into wide and back gives long, which is not the same as df:
- The
citycolumn is gone, becausepivot_tablesummed Oslo and Rome into one EU cell. Aggregation discards detail, andmeltcannot recover it. - The rows are in a different order, and the index is renumbered.
- The
pop_kcolumn may now be float, because theNaNforced the 2024 column to float.
If you need to get back to the original data, keep the original long table. Treat the wide table as a view built for reading or plotting.
Choosing a layout
| Task | Better layout |
|---|---|
| Reading a comparison across years in a report | Wide |
| `groupby`, filtering, and most plotting libraries | Long |
| Storing data that gains new categories over time | Long (a new year is a new row, not a new column) |
| Computing a change between two columns, such as 2024 minus 2023 | Wide |
A useful rule is to keep data long while you process it, and pivot to wide only for the last step.
Common errors
- A total that looks too small. The default
aggfunc="mean"was used where a sum was intended. KeyErrorinmelt.id_varsnamed a column that is actually the index. Callreset_index()first.- Columns that look like tuples. A list passed to
aggfuncorvaluesproduced a MultiIndex. Flatten it as shown above. - Numbers that became floats. A missing cell appeared. Use
fill_valueif a zero is correct, or convert later with a nullable dtype such as"Int64".
Exercise
Using the df from this chapter, write one pivot_table call that gives the average pop_k for each city (rows) and year (columns), and explain why Oslo and Rome each have no NaN but Lima does.
Show answer
df.pivot_table(index="city", columns="year", values="pop_k", aggfunc="mean"). Each city has only one row per year, so the mean of one value is that value. Oslo, Rome, and Pune have rows for both 2023 and 2024. Lima has a row only for 2023, so its 2024 cell has no data and appears as NaN. Oslo and Rome have no NaN because both years are present for them.
Exercise
Starting from wide (the sum table), write code that returns a long table with columns region, year, and pop_k and no rows with missing values.
Show answer
wide.reset_index().melt(id_vars="region", var_name="year", value_name="pop_k").dropna(subset=["pop_k"]). The reset_index call makes region an ordinary column, melt stacks the year columns, and dropna removes the SA 2024 row.