← Back to Pandas Course | Chapter 9: Reshaping Data | Lesson 2 of 6

stack/unstack()

stack moves columns into the row index and unstack moves an index level back into columns.

In this page:

  1. stack/unstack()
Syntax
python
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()

python
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
  1. Forgetting the result of stack is a Series
  2. Not handling NaN after unstack
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.