stack/unstack()
stack moves columns into the row index and unstack moves an index level back into columns.
In this page:
Syntax
stacked = df.stack()
unstacked = stacked.unstack()
stack/unstack()
stack pivots the innermost column level into the row index, producing a Series with a MultiIndex. unstack does the reverse and is often used after groupby with two keys. Missing combinations become NaN.
Note:
unstack(fill_value=0) fills empty combinations.
Example: stack/unstack()
import pandas as pd
df = pd.DataFrame({"g": ["a", "a", "b"], "k": ["x", "y", "x"], "v": [1, 2, 3]})
s = df.groupby(["g", "k"])["v"].sum()
print(s)
print(s.unstack(fill_value=0))
# Output:
# g k
# a x 1
# y 2
# b x 3
# Name: v, dtype: int64
# k x y
# g
# a 1 2
# b 3 0
Related Topics
Common Mistakes
- Forgetting the result of stack is a Series
- Not handling NaN after unstack
- Choosing the wrong level
Chapter Summary
- stack moves columns to rows
- unstack moves rows to columns
- Pairs well with groupby
- fill_value handles gaps
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: