pivot_table() (Pandas)

df.pivot_table() reshapes long data into a wide summary grid, spreading unique values of one column across the columns and aggregating the values in between. It is the spreadsheet PivotTable, in code.

Pandas

You give it index (the rows of the result), columns (the new column headers), values (the numbers to summarize), and aggfunc (how to combine them, default 'mean'). pandas computes a cross-tabulated summary, filling cells that have no data with NaN.

Unlike the stricter pivot(), pivot_table handles duplicate index/column combinations by aggregating them, which is why it needs an aggfunc. Use margins=True to add row and column totals, and fill_value to replace the NaN gaps with something like 0.

It is essentially groupby on two keys followed by an unstack, packaged into one readable call for building reports.

Syntax

df.pivot_table(index, columns, values, aggfunc='mean', fill_value=None)

Examples

Python

import pandas as pd
df = pd.DataFrame({"d": ["x", "x", "y"], "c": ["m", "n", "m"], "v": [1, 2, 3]})
print(df.pivot_table(index="d", columns="c", values="v", aggfunc="sum"))

Output:

c    m    n
d          
x  1.0  2.0
y  3.0  NaN

Learn it in a lesson

See also

Back to the Dictionary