🔶 Pandas: Pivot Tables and Reshaping
# pivot_table = aggregate + reshape (like Excel pivot)
pd.pivot_table(df,
values='sales',
index='region',
columns='quarter',
aggfunc='sum'
)
# melt = opposite of pivot (wide → long)
pd.melt(df,
id_vars=['name'],
value_vars=['Q1', 'Q2', 'Q3'],
var_name='quarter',
value_name='sales'
)
When to use pivot: When you want to see a metric across two dimensions (region × quarter). When to use melt: When your columns ARE data (Q1, Q2, Q3 are values of "quarter") and you need them as rows for analysis or plotting.