Topics in this subject
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 (not pivot) whenever the index/column combination may have duplicates — pivot will raise an error.

Interview Question: pivot vs pivot_table? pivot only reshapes and fails on duplicate keys; pivot_table aggregates duplicates via aggfunc and can add margins.