Sub topic 16
Reshaping with pivot_table and melt
This chapter assumes you can build a DataFrame, use groupby with agg, and know how an Index labels rows. Reshaping changes the layout of a table without changing the facts in it. Two layouts matter here. A long table has one observation per row. A wide table spreads one variable across several columns.
Wide and long layouts
Long data is easier to filter and group. Wide data is easier to read and plot. pivot_table goes from long to wide. melt goes from wide to long.
pivot_table: summarize into a grid
pivot_table groups rows by a row key and, optionally, a column key. It then applies an aggregation function to each group.
import pandas as pd
sales = pd.DataFrame({
"region": ["EU", "EU", "SA", "SA", "EU"],
"year": [2023, 2024, 2023, 2024, 2024],
"revenue": [10, 14, 7, 9, 6],
})
wide = sales.pivot_table(
index="region",
columns="year",
values="revenue",
aggfunc="sum",
fill_value=0,
)
print(wide)The output is:
year 2023 2024
region
EU 10 20
SA 7 9EU has two rows for 2024, and aggfunc="sum" combined them into 20. The default aggfunc is "mean", so omitting it silently averages. Combinations with no data become NaN, and fill_value=0 replaces them.
The row key becomes the Index of the result. Call reset_index() if you want it back as an ordinary column.
melt: unpivot into rows
melt takes columns and stacks them into two new columns: one for the old column names and one for their values.
long = (
wide.reset_index()
.melt(id_vars="region", var_name="year", value_name="revenue")
)
print(long)The output is:
region year revenue
0 EU 2023 10
1 SA 2023 7
2 EU 2024 20
3 SA 2024 9id_vars lists the columns that stay as identifiers. All other columns (or those named in value_vars) are melted. The round trip returned the summed data, not the original five rows, because aggregation discards detail.
Common errors
- Using
pivot_tableon data where you did not intend to aggregate. Duplicate keys are combined without warning. If you want a pure reshape that fails on duplicates, useDataFrame.pivot, which raises aValueError. - Forgetting
reset_index()beforemelt. The row key is then in the Index, andmeltdoes not see it as a column. - Expecting
yearto be a number aftermelt. It keeps the dtype of the old column labels, so check it withlong.dtypes.
Exercise
A DataFrame df has columns store, month, and units, with several rows per store and month. Write the call that produces one row per store, one column per month, and the total units in each cell, with 0 where there is no data.
Show answer
df.pivottable(index="store", columns="month", values="units", aggfunc="sum", fillvalue=0)
Exercise
Why does sales.pivot(index="region", columns="year", values="revenue") fail on the table above, while pivot_table works?
Show answer
EU has two rows for 2024. pivot cannot place two values in one cell and raises a ValueError. pivot_table aggregates the duplicates with aggfunc.