stack and unstack with MultiIndex
Rotate the innermost column level into the row index with stack() and reverse with unstack().
stack and unstack with MultiIndex is a free Pandas & NumPy Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Pandas & NumPy Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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: int64unstack(): Rows to Columns
Series.unstack() (or DataFrame.unstack()) is the inverse of stack(). It takes the innermost level of the row index and rotates it into new column labels, producing a wider result. This is functionally similar to pivot() but works directly on the index rather than on column values.
stacked = df.stack()
print(type(stacked)) # Series with MultiIndex
# Restore the original wide format
df_restored = stacked.unstack()
print(df_restored)
# Math Science
# Alice 85 92
# Bob 90 88
# Carol 78 95
# Identical to the original df!Selecting Which Level to Stack
For DataFrames with a MultiIndex on the columns, stack(level) lets you choose which level to rotate. Pass a level number (0 for outermost, -1 for innermost, the default) or a level name. Similarly, unstack(level) selects which row-index level to rotate into columns. This fine-grained control is essential for navigating complex hierarchical data structures.
# MultiIndex columns
arrays = [['Math', 'Math', 'Science', 'Science'],
['Q1', 'Q2', 'Q1', 'Q2']]
multi_cols = pd.MultiIndex.from_arrays(arrays, names=['subject', 'quarter'])
df_multi = pd.DataFrame([[85, 90, 92, 88], [78, 80, 95, 91]],
index=['Alice', 'Bob'], columns=multi_cols)
# Stack the 'quarter' level (innermost, level=-1)
print(df_multi.stack(level='quarter').head())unstack() on Specific Row Levels
When the DataFrame has a MultiIndex on rows (which is common after a groupby() on multiple columns), you can unstack() a specific row level to spread it across the columns. This is a very common pattern for building cross-tabulation style summaries without explicitly calling pivot_table().
# GroupBy produces MultiIndex rows
df2 = pd.DataFrame({
'region': ['East', 'East', 'West', 'West'],
'product': ['A', 'B', 'A', 'B'],
'sales': [100, 150, 120, 200]
})
# MultiIndex result from groupby
multi = df2.groupby(['region', 'product'])['sales'].sum()
print(multi)
# Unstack the product level into columns
wide = multi.unstack('product')
print(wide)
# product A B
# region
# East 100 150
# West 120 200Handling Missing Values in stack/unstack
When unstack() is called and not every row-index combination exists for every column level, Pandas fills missing cells with NaN. Conversely, stack() by default drops rows that are entirely NaN. You can control this with the dropna parameter: pass stack(dropna=False) to keep NaN rows.
# Incomplete data: West has no product B
df3 = df2[df2['product'] != 'B'].copy()
multi3 = df3.groupby(['region', 'product'])['sales'].sum()
wide3 = multi3.unstack('product', fill_value=0)
print(wide3)
# product A B
# region
# East 100 0 <- B filled with 0 instead of NaN
# West 120 0stack() Then Compute on Rows
A powerful pattern is to stack() a wide DataFrame to convert columns into rows, apply a row-wise operation like filtering or groupby, then unstack() to return to wide format. This avoids the need to write column-by-column loops and keeps your code vectorised and readable. It is especially useful for applying the same transformation to every column simultaneously.
# Normalise each column by its column mean using stack/compute/unstack
normalised = (
df.stack()
.groupby(level=1)
.transform(lambda s: (s - s.mean()) / s.std())
.unstack()
)
print(normalised.round(2))
# Math Science
# Alice 0.0 0.39
# Bob 1.13 -1.09
# Carol -1.13 0.71stack() for Plotting
Just like melt(), stack() converts data to long format, which is what Seaborn and many Matplotlib helpers expect. The main difference is that stack() operates on the column index and preserves the MultiIndex structure, while melt() produces a flat long DataFrame. Both lead to similar plotting workflows.
# Prepare data for line plot using stack
long = df.stack().reset_index()
long.columns = ['student', 'subject', 'score']
print(long)
# student subject score
# 0 Alice Math 85
# 1 Alice Science 92
# ...
# Ready for: sns.barplot(data=long, x='student', y='score', hue='subject')swaplevel() for Index Reordering
After stacking, the innermost row level is the original column name. Sometimes you want the outer level to be the variable name and the inner level to be the original row index. Use swaplevel() on the MultiIndex to swap the order of two levels, and then sort_index() to restore a clean ordering.
stacked = df.stack() # MultiIndex: (student, subject)
swapped = stacked.swaplevel() # MultiIndex: (subject, student)
swapped = swapped.sort_index()
print(swapped)
# subject student
# Math Alice 85
# Bob 90
# Carol 78
# Science Alice 92
# Bob 88
# Carol 95When to Use stack vs melt vs pivot
Choose stack() when working with MultiIndex column DataFrames and you want to reduce the column levels by one. Choose melt() when you have a flat DataFrame and want to go from wide to long format with control over which columns become rows. Choose pivot()/pivot_table() to go from long back to wide. These three tools cover all wide/long reshaping needs in Pandas.
# Decision guide (comment, not executable standalone):
# MultiIndex columns -> want fewer levels: use stack()
# Flat wide -> need long format for plotting/ML: use melt()
# Long -> need wide summary table: use pivot_table()
# Wide -> back to long: use melt() or stack()
# Example: stack when you have pivot_table output (MultiIndex cols)
tbl = df2.groupby(['region', 'product'])['sales'].sum().unstack()
long_again = tbl.stack().rename('sales').reset_index()
print(long_again)Practical Summary: Reshaping Cheatsheet
Here is a concise mental model: stack() — columns collapse into rows, DataFrame gets narrower and taller. unstack() — rows expand into columns, DataFrame gets wider and shorter. melt() — named columns collapse into a key-value pair (two new columns). pivot_table() — a key-value column expands into multiple columns. All four are reversible, and knowing which direction to go is simply a matter of deciding whether the target analysis prefers wide or long format.
# stack/unstack cycle
df_wide = df.copy() # wide format
df_long = df_wide.stack() # long via stack
df_wide2 = df_long.unstack() # back to wide
# melt/pivot cycle
df_melted = df_wide.melt(id_vars=[]) # wide -> long
# df_pivoted = df_melted.pivot(...) # long -> wide
print('Original shape: ', df_wide.shape)
print('After stack: ', df_long.shape)
print('After unstack: ', df_wide2.shape)Quick Check
Test your understanding of stack and unstack with MultiIndex from this lesson.
Lesson Recap
In this lesson you learned: stack() rotates column labels into the row index to produce a longer, narrower result; unstack() does the reverse, rotating a row-index level into columns; both work with MultiIndex structures from groupby operations; and swaplevel() lets you reorder index levels. Next up we explore pd.crosstab() for quick frequency tables between categorical columns.
Frequently asked questions
Is the “stack and unstack with MultiIndex” lesson free?
Yes — the full text of “stack and unstack with MultiIndex” is free to read here on the web, and the Pandas & NumPy Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Pandas & NumPy Academy course, upgrade to CoddyKit PRO.
What will I learn in “stack and unstack with MultiIndex”?
Rotate the innermost column level into the row index with stack() and reverse with unstack(). You practise Pandas & NumPy Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Pandas & NumPy Academy?
No prior experience is required. Pandas & NumPy Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “stack and unstack with MultiIndex” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Pandas & NumPy Academy lesson?
Yes. Every Pandas & NumPy Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- pivot_table: Cross-Tabulation
- melt: Wide to Long Format
- stack and unstack with MultiIndex
- crosstab for Frequency Tables