0PricingLogin
Pandas & NumPy Academy · Lesson

stack and unstack with MultiIndex

Rotate the innermost column level into the row index with stack() and reverse with unstack().

Introduction to stack and unstack

stack() and unstack() are Pandas reshaping tools that move data between the row index and the column index. They are particularly useful when working with DataFrames that have a MultiIndex on either axis. stack() takes the innermost column level and rotates it into the innermost row level, while unstack() does the reverse.

stack(): Columns to Rows

DataFrame.stack() pivots the innermost level of the column labels into the innermost level of the row index, producing a longer, narrower result. If the original DataFrame had simple (non-multi) columns, the result is a Series with a MultiIndex. If the columns had multiple levels, stack() reduces the column levels by one.

import pandas as pd

df = pd.DataFrame({
    'Math': [85, 90, 78],
    'Science': [92, 88, 95]
}, index=['Alice', 'Bob', 'Carol'])

print(df)
#        Math  Science
# Alice    85       92
# Bob      90       88
# Carol    78       95

stacked = df.stack()
print(stacked)
# Alice    Math       85
#          Science    92
# Bob      Math       90
#          Science    88
# Carol    Math       78
#          Science    95
# dtype: int64

All lessons in this course

  1. pivot_table: Cross-Tabulation
  2. melt: Wide to Long Format
  3. stack and unstack with MultiIndex
  4. crosstab for Frequency Tables
← Back to Pandas & NumPy Academy