使用 MultiIndex 进行 stack 和 unstack
使用 stack() 将最内层列级别旋转到行索引中,并使用 unstack() 还原。
使用 MultiIndex 进行 stack 和 unstack 是 CoddyKit 上的免费 Pandas & NumPy Academy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Pandas & NumPy Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Pandas & NumPy Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
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.
常见问题解答
「使用 MultiIndex 进行 stack 和 unstack」课时是免费的吗?
是的 — 「使用 MultiIndex 进行 stack 和 unstack」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Pandas & NumPy Academy 课程的其余内容,请升级到 CoddyKit PRO。 Pandas & NumPy Academy 课程共包含 4 节课。
「使用 MultiIndex 进行 stack 和 unstack」这节课中我会学到什么?
使用 stack() 将最内层列级别旋转到行索引中,并使用 unstack() 还原。 你通过在浏览器中直接运行的动手代码来练习 Pandas & NumPy Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Pandas & NumPy Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Pandas & NumPy Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「使用 MultiIndex 进行 stack 和 unstack」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Pandas & NumPy Academy 课中编写并运行代码吗?
能。每节 Pandas & NumPy Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- pivot_table:交叉表
- melt:从宽格式转换为长格式
- 使用 MultiIndex 进行 stack 和 unstack
- 使用 crosstab 创建频数表