Pandas df.stack() Function
df.stack() is a member method of DataFrame, used toConvert column indices to row indices. It "stacks" the columns of wide-format data into rows, producing a Series or DataFrame with a hierarchical index.
This is an important data reshaping operation, often used together with unstack() to achieve mutual conversion of data.
Word meaning: stack It means "stack/pile up"; here it refers to stacking column data into rows, converting a wide table into a long table.
Basic syntax and parameters
df.stack() is an instance method of DataFrame, called via the dot operator.
Syntax format
DataFrame.stack(level=-1, dropna=True)
Parameter Description
- Parameters:
level - Type: int, str, a list of int, or a list of str.
- Description: Specify the level(s) to stack. For a MultiIndex, you can specify a concrete level number (starting from 0) or a level name. The default is -1, meaning the innermost level.
- Parameters:
dropna - Type: boolean.
- Description: Whether to drop rows in the result that are all NaN. The default is True, meaning rows containing all NaN values are removed.
Function description
- Return Value: Returns a Series or DataFrame. If only one column of the original DataFrame is stacked, a Series is returned; otherwise a DataFrame is returned.
- effect: Converts column indices to row indices, producing a longer data format. Stacked data is in "long format", convenient for statistical analysis or visualization.
Example
Let us thoroughly master df.stack() through a series of examples from simple to complex.
Example 1: Basic Usage - Converting Columns to Rows
Example
import
pandas
as
pd
import
numpy
as
np
1. Create wide-format data (one column per quarter)
df
=
pd.
DataFrame
(
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
]
,
'Q1'
:
[
100
,
150
,
200
]
,
'Q2'
:
[
120
,
160
,
210
]
,
'Q3'
:
[
130
,
170
,
220
]
}
)
(
"=== Original wide-format data ==="
)
(
df
)
(
f
"Column names: {df.columns.tolist()}"
)
2. Use df.stack() to convert columns to rows
stacked
=
df.
stack
(
)
(
"n=== df.stack() Result ==="
)
(
stacked
)
(
f
"nType: {type(stacked)}"
)
3. Convert the result to a DataFrame for viewing
(
"n=== Converted to DataFrame ==="
)
stacked_df
=
stacked.
reset_index
(
)
stacked_df.
columns
=
[
'name'
,
'quarter'
,
'sales'
]
(
stacked_df
)
Expected output:
=== 原始宽格式数据 ===
name Q1 Q2 Q3
0 Alice 100 120 130
1 Bob 150 160 170
2 Charlie 'Q2', 'Q3'], columns=['name', 'quarter', 'sales']
...
Code analysis:
- The original data is in wide format, with Q1, Q2, Q3 as three columns of quarterly data.
stack()"Stack" the three columns Q1, Q2, Q3 into rows.- The result is a Series with two index levels: the outer level is the original row index and the inner level is the original column names (quarters).
- After stacking, the data becomes "long format", with only one quarter value per row.
Example 2: Stacking Multi-Level Column Indices
When a DataFrame has multi-level column indices, you can specify which level to stack.
Example
import
pandas
as
pd
import
numpy
as
np
1. Create data with a multi-level column index
Outer level: product type (Electronics, Furniture)
Inner level: quarter (Q1, Q2)
df
=
pd.
DataFrame
(
[
[
100
,
110
,
200
,
210
]
,
[
150
,
160
,
180
,
190
]
]
,
index
=
[
'Store_A'
,
'Store_B'
]
,
columns
=
pd.
MultiIndex
.
from_tuples
(
[
(
'Electronics'
,
'Q1'
)
,
(
'Electronics'
,
'Q2'
)
,
(
'Furniture'
,
'Q1'
)
,
(
'Furniture'
,
'Q2'
)
]
,
names
=
[
'Product'
,
'Quarter'
]
)
)
(
"=== Original data (multi-level column index) ==="
)
(
df
)
(
f
"Column index levels: {df.columns.names}"
)
2. Stack the inner columns (default, level=-1)
(
"n=== Stack inner columns (level=-1) ==="
)
stacked_inner
=
df.
stack
(
)
(
stacked_inner
)
3. Stack the outer columns
(
"n=== Stack outer columns (level=0) ==="
)
stacked_outer
=
df.
stack
(
level
=
0
)
(
stacked_outer
)
4. Stack all columns (producing a longer format)
(
"n=== Stack all columns ==="
)
stacked_all
=
df.
stack
(
level
=
[
0
,
1
]
)
(
stacked_all
)
Expected output:
=== 原始数据(多层列索引)===
Product Electronics Furniture
Quarter Q1 Q2 Q1 Q
...
Code analysis:
- For a DataFrame with a multi-level column index, column names are in tuple form: (Product, Quarter).
level=-1(Default) Stack the innermost level, the Quarter level, leaving Product as columns.level=0Stack the outer level, the Product level, leaving Quarter as columns.- This flexibility lets you choose which level to stack based on your analysis needs.
Example 3: Handling Missing Values
Use dropna This parameter controls how missing values are handled.
Example
import
pandas
as
pd
import
numpy
as
np
1. Create data containing missing values
df
=
pd.
DataFrame
(
{
'name'
:
[
'Alice'
,
'Bob'
]
,
'Math'
:
[
100
,
np.
nan
]
,
'English'
:
[
90
,
85
]
,
'Science'
:
[
np.
nan
,
95
]
}
)
(
"=== Original data (with missing values) ==="
)
(
df
)
2. dropna=True (default), drop rows that are all NaN
(
"n=== dropna=True (default) ==="
)
stacked_drop
=
df.
stack
(
dropna
=
True
)
(
stacked_drop
)
3. dropna=False, keep NaN values
(
"n=== dropna=False ==="
)
stacked_keep
=
df.
stack
(
dropna
=
False
)
(
stacked_keep
)
4. Practical application: organize the stacked result into an analyzable long format
(
"n=== Organized into long-format DataFrame ==="
)
result
=
df.
set_index
(
'name'
)
.
stack
(
)
.
reset_index
(
)
result.
columns
=
[
'name'
,
'subject'
,
'score'
]
(
result
)
5. Drop missing values
result_clean
=
result.
dropna
(
)
(
"n=== After dropping missing values ==="
)
(
result_clean
)
Expected output:
=== 原始数据(包含缺失值)===
name Math English Science
0 Alice 100.0 90.0 NaN
1 Bob NaN 85.0 95.0
2=== 堆叠内层列 (level=-1) ===
Store_A Electronics Q1 100
Q2 110
Furniture Q1 200
Q2 210
Store_B Electronics Q1 150
...
Code analysis:
dropna=True(By default) rows where all values are NaN are dropped.- In data analysis, you usually keep the original data and then drop missing values as needed.
- After stacking, use
reset_index()to convert the hierarchical index into ordinary columns for easier subsequent processing.
Example 4: Using stack and unstack Together
stack() and unstack() They are inverse operations; used together they enable flexible data reshaping.
Example
import
pandas
as
pd
1. Create initial data
df
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'B'
,
'C'
]
,
'North'
:
[
100
,
150
,
200
]
,
'South'
:
[
180
,
170
,
160
]
,
'East'
:
[
190
,
200
,
210
]
}
)
(
"=== Original data ==="
)
(
df
)
2. Use unstack to turn regions into columns (first convert to a multi-level index)
df_indexed
=
df.
set_index
(
'product'
)
(
"n=== After setting the index ==="
)
(
df_indexed
)
3. Use stack to turn columns into rows (stack is the inverse of unstack)
(
"n=== unstack + stack round trip ==="
)
First unstack
unstacked
=
df_indexed.
unstack
(
)
(
"unstack Result:"
)
(
unstacked
)
Then stack back
restacked
=
unstacked.
stack
(
)
(
"nStacked back:"
)
(
restacked
)
4. Complete example: create a multi-level index and then convert
(
"n=== Multi-level index conversion ==="
)
Create a multi-level index DataFrame
multi_df
=
pd.
DataFrame
(
[
[
100
,
110
]
,
[
150
,
160
]
]
,
index
=
pd.
MultiIndex
.
from_tuples
(
[
(
'A'
,
'2023'
)
,
(
'B'
,
'2023'
)
]
,
names
=
[
'product'
,
'year'
]
)
,
columns
=
[
'North'
,
'South'
]
)
(
"Original multi-level index data:"
)
(
multi_df
)
unstack year
(
"nunstack year:"
)
(
multi_df.
unstack
(
level
=
'year'
)
)
unstack columns
(
"nunstack columns (to columns):"
)
(
multi_df.
unstack
(
level
=
'columns'
)
)
Expected output:
=== unstack + stack 往返 ===
unstack 结果:
product
North A 100
B 150
C 200
South A 180
B 170
...
Code analysis:
stack()Convert column indices to row indices, turning a wide table into a long table.unstack()Convert row indices to column indices, turning a long table into a wide table.- Used together, they can reshape data into any desired form.
- For data analysis, understanding the inverse relationship between these two operations is very important.
Tip:
stack()andunstack()It is a core tool for data reshaping.stack()It "piles" columns into rows (wide to long),unstack()and "unpiles" rows into columns (long to wide).
Common Pandas functions