When would you use pivot_table instead of groupby in pandas?
pivot_table is groupby with the second key spread across columns, giving a cross-tab style summary. Use it when you want a grid for reading or charting, and groupby when you want a long list of groups.
Explain it simply
A groupby with two keys gives a long list: one line per city and month. A pivot table lays the same numbers out as a grid, cities down the side and months across the top, just like an Excel pivot table.
Example
import pandas as pd
s = pd.DataFrame({
"city": ["Pune", "Pune", "Delhi", "Delhi"],
"month": ["Jan", "Feb", "Jan", "Feb"],
"sales": [10, 20, 30, 40],
})
p = s.pivot_table(index="city", columns="month", values="sales", aggfunc="sum")
print(p)
# month Feb Jan
# city
# Delhi 40 30
# Pune 20 10Columns come out alphabetically (Feb before Jan), so convert month to an ordered category if you want calendar order.
Handy options:
fill_value=0fills combinations that never occurred.margins=Trueadds row and column totals.pivot(without table) only reshapes and fails on duplicate index and column pairs, whilepivot_tableaggregates duplicates.
What to say in the interview
"pivot_table is a groupby plus a reshape. I use it for a readable grid or a heatmap and groupby for pipelines. Unlike pivot, it handles duplicates by aggregating them, and I can add margins and fill_value for totals and gaps."
Common mistakes
- Using pivot on data with repeated key pairs and getting a ValueError.