Pivot Tables, Melt, Stack, and Unstack
Pandas Basics
2 min read
This section is 2 min read, full guide is 30 min read
Published Sep 29 2025, updated Oct 24 2025
21
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
PandasPython
There are various ways to reshape your data between wide, long, and hierarchical forms.
- Pivot Table → reshapes data from long → wide, useful for summarisation (like Excel pivot tables).
- Melt → reshapes data from wide → long, useful for tidy data & plotting.
- Stack → Takes columns and “stacks” them into the row index.
- Unstack → Moves an index level back into columns.
Pivot Table
A pivot table summarises and reshapes data by aggregating values across one or more categories.
Syntax:
pd.pivot_table(
data,
values=None,
index=None,
columns=None,
aggfunc="mean",
fill_value=None,
margins=False
)
Copy to Clipboard
Key Parameters:
data→ DataFramevalues→ column(s) to aggregateindex→ row groupingcolumns→ column groupingaggfunc→ aggregation function ('mean','sum','count', custom funcs)fill_value→ replace missing values in resultmargins=True→ adds totals (like Excel “All”)
Example:
import pandas as pd
data = {
"Department": ["Sales", "Sales", "IT", "IT", "HR"],
"Employee": ["Alice", "Bob", "Charlie", "Dave", "Eve"],
"Salary": [50000, 60000, 70000, 80000, 45000],
}
df = pd.DataFrame(data)
pivot = pd.pivot_table(
df,
values="Salary",
index="Department",
aggfunc="mean"
)
print(pivot)
Copy to Clipboard
Output:
Salary
Department
HR 45000
IT 75000
Sales 55000
Copy to Clipboard
Melt
melt() is the reverse of pivot. It transforms a wide DataFrame into a long (tidy) format.
Syntax:
pd.melt(
frame,
id_vars=None,
value_vars=None,
var_name="variable",
value_name="value"
)
Copy to Clipboard
Key Parameters:
frame→ DataFrameid_vars→ columns to keep fixed (like identifiers)value_vars→ columns to unpivotvar_name→ new column name for variable namesvalue_name→ new column name for values
Example:
df = pd.DataFrame({
"Employee": ["Alice", "Bob"],
"Sales_Q1": [200, 150],
"Sales_Q2": [210, 160]
})
melted = pd.melt(
df,
id_vars=["Employee"],
value_vars=["Sales_Q1", "Sales_Q2"],
var_name="Quarter",
value_name="Sales"
)
print(melted)
Copy to Clipboard
Output:
Employee Quarter Sales
0 Alice Sales_Q1 200
1 Bob Sales_Q1 150
2 Alice Sales_Q2 210
3 Bob Sales_Q2 160
Copy to Clipboard
Stack
Takes columns and “stacks” them into the row index. Useful for moving from a wide to a longer DataFrame, especially when you already have a MultiIndex.
Example:
import pandas as pd
df = pd.DataFrame({
"Name": ["Alice", "Bob"],
"Math": [90, 80],
"Science": [85, 95]
})
print("Original DF:\n", df)
stacked = df.set_index("Name").stack()
print("\nStacked:\n", stacked)
Copy to Clipboard
Output:
Original DF:
Name Math Science
0 Alice 90 85
1 Bob 80 95
Stacked:
Name
Alice Math 90
Science 85
Bob Math 80
Science 95
dtype: int64
Copy to Clipboard
Notice how Math and Science moved into the row index. The result is a Series with a MultiIndex
Unstack
Moves an index level back into columns and restores the wider form.
Example:
unstacked = stacked.unstack()
print(unstacked)
Copy to Clipboard
Output:
Math Science
Name
Alice 90 85
Bob 80 95
Copy to Clipboard














