Pandas df.unstack() Function
df.unstack() is a member method of DataFrame, used toConvert row indexes to column indexes. It "unstacks" data with a hierarchical index, moving one or more row levels into the columns.
This is an important data reshaping operation, often used together with stack() to achieve mutual conversion of data.
Word meaning: unstack means "to take apart and spread out"; here it refers to "unstacking" row indexes into columns, turning a long table into a wide one.
Basic syntax and parameters
df.unstack() is an instance method of DataFrame, called via the dot operator.
Syntax format
DataFrame.unstack(level=-1, fill_value=None)
Parameter Description
- Parameters:
level - Type: int, str, a list of int, or a list of str.
- Description: Specifies the level(s) to unstack into columns. For a MultiIndex, you can specify a specific level number (starting from 0) or a level name. The default is -1, meaning the innermost level.
- Parameters:
fill_value - Type: scalar or None.
- Description: The value used to fill missing values produced by the unstack operation. The default is None, which preserves NaN.
Function description
- Return Value: Returns a Series or a DataFrame. If only one row level of the original DataFrame is unstacked, a Series is returned; otherwise a DataFrame is returned.
- effect: Moves one or more levels of the row index into the column index, producing a wider data format. The unstacked data is in "wide format", making it easy to view and compare.
Example
Let us thoroughly master df.unstack() through a series of examples from simple to complex.
Example 1: Basic usage - converting rows to columns
Example
import
pandas
as
pd
1. Create long-format data
df
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'A'
,
'B'
,
'B'
,
'C'
,
'C'
]
,
'region'
:
[
'North'
,
'South'
,
'North'
,
'South'
,
'North'
,
'South'
]
,
'sales'
:
[
100
,
150
,
200
,
180
,
220
,
250
]
}
)
(
"=== Original long-format data ==="
)
(
df
)
2. Set a hierarchical index
df_indexed
=
df.
set_index
(
[
'product'
,
'region'
]
)
(
"n=== After setting the hierarchical index ==="
)
(
df_indexed
)
3. Use df.unstack() to convert the inner index into columns
unstacked
=
df_indexed.
unstack
(
)
(
"n=== df.unstack() result ==="
)
(
unstacked
)
4. Simplify the view
(
"n=== Sales only ==="
)
(
unstacked
[
'sales'
]
)
Expected output:
=== 原始长格式数据 ===
product region sales
0 A North 100
1 A South 150
2 B North 200
3 B South 180
4 C North 220
5 C South 250
n=== 设置层次化索引后 ===
sales
product region
A North 100
South 150
B North 200
South 180
C North 220
South 250
n=== df.unstack() 结果 ===
sales
region North South
product
A 100 150
B 200 180
C 220 250
n=== 只看销售额 ===
region North South
product
A 100 150
B 200 180
C 220 250
Code analysis:
- The original data is in long format, with each row recording the sales of a product in a certain region.
- Use
set_index()Create a hierarchical index (product as the outer level, region as the inner level). unstack()Move the inner index region into the columns.- The result is in wide format, allowing intuitive comparison of sales data for different products across regions.
Example 2: Unstacking a MultiIndex
When a DataFrame has multiple row index levels, you can specify which level to unstack.
Example
import
pandas
as
pd
1. Create data with a multi-level row index
df
=
pd.
DataFrame
(
{
'year'
:
[
2023
,
2023
,
2023
,
2023
,
2024
,
2024
,
2024
,
2024
]
,
'quarter'
:
[
'Q1'
,
'Q1'
,
'Q2'
,
'Q2'
,
'Q1'
,
'Q1'
,
'Q2'
,
'Q2'
]
,
'product'
:
[
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
,
'A'
,
'B'
]
,
'sales'
:
[
100
,
150
,
200
,
180
,
220
,
250
,
230
,
270
]
}
)
(
"=== Original data ==="
)
(
df
)
2. Set a multi-level index
df_indexed
=
df.
set_index
(
[
'year'
,
'quarter'
,
'product'
]
)
(
"n=== Set multi-level index ==="
)
(
df_indexed
)
3. Unstack the innermost level (product, default level=-1)
(
"n=== Unstack the product level (default) ==="
)
unstacked_inner
=
df_indexed.
unstack
(
)
(
unstacked_inner
[
'sales'
]
)
4. Unstack the middle level (quarter)
(
"n=== Unstack the quarter level ==="
)
unstacked_quarter
=
df_indexed.
unstack
(
level
=
'quarter'
)
(
unstacked_quarter
[
'sales'
]
)
5. Unstack the outer level (year)
(
"n=== Unstack the year level ==="
)
unstacked_year
=
df_indexed.
unstack
(
level
=
'year'
)
(
unstacked_year
[
'sales'
]
)
6. Unstack multiple levels at once
(
"n=== Unstack year and product together ==="
)
unstacked_multi
=
df_indexed.
unstack
(
level
=
[
'year'
,
'product'
]
)
(
unstacked_multi
[
'sales'
]
)
Expected output:
=== 原始数据 ===
year quarter product sales
0 2023 Q1 A 100
1 2023 Q1 B 150
2 2023 Q2 A 200
3 2023 Q2 B 180
4 2024 Q1 A 220
5 2024 Q1 B 250
6 2024 Q2 A 230
7 2024 Q2 B 270
n=== 设置多层索引 ===
sales
year quarter product
2023 Q1 A 100
B 150
Q2 A 200
B 180
2024 Q1 A 220
B 250
Q2 A 230
B 270
n=== 展开 product 层(默认)===
product A B
year quarter
2023 Q1 100 150
Q2 200 180
2024 Q1 220 250
Q2 230 270
n=== 展开 quarter 层 ===
quarter Q1 Q2
year product
2023 A 100 200
B 150 180
2024 A 220 230
B 250 270
n=== 展开 year 层 ===
year 2023 2024
quarter product
Q1 A 100 220
B 150 250
Q2 A 200 230
B 180 270
n=== 同时展开 year 和 product ===
year 2023 2024
product A B A B
quarter
Q1 100 150 220 250
Q2 200 180 230 270
Code analysis:
- For a DataFrame with a MultiIndex, you can use the
levelparameter to specify which level to unstack. - Default
level=-1Unstack the innermost level (product). - Unstacking different levels produces different data layouts, making it easier to analyze the data from different perspectives.
Example 3: Handling missing values with fill_value
Use fill_value The parameter can fill missing values produced after unstacking.
Example
import
pandas
as
pd
import
numpy
as
np
1. Create incomplete data (not every product-region combination has data)
df
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'A'
,
'B'
,
'C'
]
,
'region'
:
[
'North'
,
'South'
,
'North'
,
'East'
]
,
'sales'
:
[
100
,
150
,
200
,
220
]
}
)
(
"=== Original data (incomplete) ==="
)
(
df
)
2. Create a hierarchical index and unstack
df_indexed
=
df.
set_index
(
[
'product'
,
'region'
]
)
(
"n=== Hierarchical index ==="
)
(
df_indexed
)
3. Do not fill missing values
(
"n=== Do not fill missing values ==="
)
unstacked
=
df_indexed.
unstack
(
)
(
unstacked
)
(
f
"Missing value count: {unstacked['sales'].isna().sum().sum()}"
)
4. Fill missing values with fill_value=0
(
"n=== fill_value=0 ==="
)
unstacked_fill
=
df_indexed.
unstack
(
fill_value
=
0
)
(
unstacked_fill
)
(
f
"Missing value count: {unstacked_fill['sales'].isna().sum().sum()}"
)
Expected output:
=== 原始数据(不完整)===
product region sales
0 A North 100
1 A South 150
2 B North 200
3 C East 220
n=== 层次化索引 ===
sales
product region
A North 100
South 150
B North 200
C East 220
n=== 不填充缺失值 ===
sales
region East North South
product
A NaN 100.0 150.0
B NaN 200.0 NaN
C 220.0 NaN NaN
缺失值数量: 5
n=== fill_value=0 ===
sales
region East North South
product
A 0 100 150
B 0 200 0
C 220 0 0
缺失值数量: 0
Code analysis:
- When the original data is incomplete, unstacking produces missing values (NaN).
- Use
fill_valueThe parameter lets you specify a fill value to avoid errors in later calculations. - Filling with 0 usually means "no data" or "this combination does not exist".
Example 4: Using unstack together with stack
unstack() and stack() They are inverse operations; used together they enable flexible data reshaping.
Example
import
pandas
as
pd
1. Create initial wide-format data
df
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'B'
,
'C'
]
,
'North'
:
[
100
,
150
,
200
]
,
'South'
:
[
180
,
170
,
160
]
,
'East'
:
[
190
,
200
,
210
]
}
)
(
"=== Original wide-format data ==="
)
(
df
)
2. First use stack to convert to long format
(
"n=== step 1: stack converts to long format ==="
)
stacked
=
df.
set_index
(
'product'
)
.
stack
(
)
(
stacked
)
3. Then unstack back (to verify reversibility)
(
"n=== step 2: unstack converts back to wide format ==="
)
restored
=
stacked.
unstack
(
)
(
restored
)
4. Practical example: rearranging data
(
"n=== Practical example: moving region into columns ==="
)
Original: product as row index, region as columns
Goal: region as row index, product as columns
result
=
df.
set_index
(
'product'
)
.
unstack
(
)
.
unstack
(
level
=
1
)
(
result
)
5. Use reorder_levels to adjust the level order
(
"n=== Adjust levels with reorder_levels ==="
)
Create a two-level index
df_multi
=
pd.
DataFrame
(
[
[
100
,
200
]
,
[
150
,
180
]
,
[
190
,
210
]
]
,
index
=
pd.
MultiIndex
.
from_tuples
(
[
(
'A'
,
'North'
)
,
(
'B'
,
'North'
)
,
(
'C'
,
'North'
)
]
,
names
=
[
'product'
,
'region'
]
)
,
columns
=
[
'2023'
,
'2024'
]
)
(
"Original data:"
)
(
df_multi
)
Adjust the level order
(
"nAfter adjustment (year as the outer level):"
)
(
df_multi.
unstack
(
level
=
'region'
)
)
Expected output:
=== 原始宽格式数据 ===
product North South East
0 A 100 180 190
1 B 150 170
...
Code analysis:
stack()andunstack()are a pair of inverse operations.- Stacking first and then unstacking can theoretically restore the original shape (ignoring differences in fill values).
- Different combinations of levels can produce different data layouts.
- In real data analysis, you often need to reshape data repeatedly to suit different analytical needs.
Tip:
unstack()andstack()It is a core tool for data reshaping.unstack()splits rows into columns (long to wide),stack()piles columns into rows (wide to long).
Common Pandas functions