Pivot Tables
A grouped summary laid out as a grid.
Rows, columns and a value
pivot_table groups by two keys and lays the result out as a grid rather than a long list. Same numbers, different shape.
import pandas as pd
df = pd.DataFrame({"subject": ["m", "m", "a"], "year": [10, 11, 10], "score": [90, 80, 70]})
out = pd.pivot_table(df, index="subject", columns="year", values="score", aggfunc="mean")
print(out.shape)
Combinations with no rows
A grid has a cell for every pair, including those the data never had. Those come out missing, and fill_value decides what a reader sees there.
import pandas as pd
df = pd.DataFrame({"a": ["x"], "b": [1], "v": [5]})
out = pd.pivot_table(df, index="a", columns="b", values="v", aggfunc="mean", fill_value=0)
print(out.values.tolist())
Exercise
Try It YourselfWrite grid_shape(df) that pivots score with subject down the rows and year across the columns, and returns the shape of the result.
Press Run to see output