Pandas
1 min read
Updated 4 Aug 2026
11. Pivot Tables & Reshaping
df = pd.DataFrame({
df = pd.DataFrame({
'date':['J','J','F','F'], 'city':['NYC','LA','NYC','LA'],
'sales':[10,20,30,40]})
# pivot: reshape (no aggregation) -> errors on duplicate index/col pairs
df.pivot(index='date', columns='city', values='sales')
# pivot_table: reshape WITH aggregation
df.pivot_table(index='date', columns='city', values='sales',
aggfunc='sum', margins=True) # margins adds totals
# melt: wide -> long (unpivot)
wide = pd.DataFrame({'id':[1,2], 'jan':[10,20], 'feb':[30,40]})
wide.melt(id_vars='id', var_name='month', value_name='sales')
# stack / unstack: move between columns and index levels
df.set_index(['date','city']).unstack() # inner index -> columns
# stack does the reverse
# crosstab: frequency table
pd.crosstab(df['date'], df['city'])
| Function | Direction | Aggregates? |
|---|---|---|
pivot |
long → wide | No (errors on dup keys) |
pivot_table |
long → wide | Yes (aggfunc) |
melt |
wide → long | No |
stack |
columns → index | No |
unstack |
index → columns | No |
crosstab |
build frequency table | counts by default |
💡 Tip: Use
pivot_table(notpivot) whenever the index/column combination may have duplicates —pivotwill raise an error.
⭐ Interview Question:
pivotvspivot_table?pivotonly reshapes and fails on duplicate keys;pivot_tableaggregates duplicates viaaggfuncand can add margins.