Pandas pd.melt() function
pd.melt() is a top-level function in the Pandas library used toconvert wide format to long format. It "melts" wide-format data with multiple columns into long format, similar to the unpivot operation in Excel.
This is one of the most commonly used functions in data reshaping, especially useful when data needs to be converted to long format before visualization, or when multiple columns need to be merged into one.
Word meaning: melt means "melt", here referring to "melting" a wide-table structure into a long-table structure, similar to gathering multiple columns of data together.
Basic syntax and parameters
pd.melt() is a top-level function in the Pandas library used to convert wide-format data to long format.
Syntax format
pd.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None)
Parameter Description
- Parameters:
frame - Type: DataFrame.
- Description: Required parameter. The source DataFrame, i.e., the data to convert from wide to long format.
- Parameters:
id_vars - Type: column name, list of tuples, or None.
- Description: Columns used as identifiers (ID), which remain unchanged after the conversion. Can be a single column name or a list of column names. If not specified, all columns are treated as value_vars.
- Parameters:
value_vars - Type: column name, list of tuples, or None.
- Description: The columns to "melt", i.e., which columns to convert into rows. If not specified, all columns except id_vars are converted.
- Parameters:
var_name - Type: string or None.
- Description: The name of the generated column for storing the original column names. Defaults to 'variable'.
- Parameters:
value_name - Type: string.
- Description: The name of the generated value column. Defaults to 'value'.
- Parameters:
col_level - Type: int, str, or None.
- Description: If the columns are a MultiIndex, specify the level(s) to melt.
Function description
- Return Value: Returns a DataFrame with data converted from wide format to long format.
- effect: "Melts" the values of multiple columns into two columns: one storing the original column names (variable) and one storing the corresponding values (value).
Example
Let us thoroughly master pd.melt() through a series of examples from simple to complex.
Example 1: Basic usage - simple wide-to-long conversion
Example
import
pandas
as
pd
1. Create wide-format data (one column per quarter)
df
=
pd.
DataFrame
(
{
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
]
,
'Q1_sales'
:
[
100
,
150
,
200
]
,
'Q2_sales'
:
[
120
,
160
,
210
]
,
'Q3_sales'
:
[
130
,
170
,
220
]
}
)
(
"=== Original wide-format data ==="
)
(
df
)
2. Convert to long format using pd.melt()
melted
=
pd.
melt
(
df
,
id_vars
=
[
'name'
]
,
value_vars
=
[
'Q1_sales'
,
'Q2_sales'
,
'Q3_sales'
]
)
(
"n=== pd.melt() convert to long format ==="
)
(
melted
)
3. Customize column names
melted_custom
=
pd.
melt
(
df
,
id_vars
=
[
'name'
]
,
value_vars
=
[
'Q1_sales'
,
'Q2_sales'
,
'Q3_sales'
]
,
var_name
=
'quarter'
,
value_name
=
'sales'
)
(
"n=== Custom column names ==="
)
(
melted_custom
)
Expected output:
=== 原始宽格式数据 ===
name Q1_sales Q2_sales Q3_sales
0 Alice 100 120 130
1 Bob 150 160 170
2 Charlie 200 210 220
=== pd.melt() 转换为长格式 ===
name variable value
0 Alice Q1_sales 100
1 Bob Q1_sales 150
2 Charlie Q1_sales 200
3 Alice Q2_sales 120
4 Bob Q2_sales 160
5 Charlie Q2_sales 210
6 Alice Q3_sales 130
7 Bob Q3_sales 170
8 Charlie Q3_sales 220
=== 自定义列名 ===
name quarter sales
0 Alice Q1_sales 100
1 Bob Q1_sales 150
2 Charlie Q1_sales 200
3 Alice Q2_sales 200
Code analysis:
- The original data is in wide format, with one person per row, and Q1, Q2, Q3 are the sales data columns for three quarters.
id_vars=['name']Specify the name column to remain unchanged as the identifier.value_vars=['Q1_sales', 'Q2_sales', 'Q3_sales']Specify the columns to melt.- The result adds a variable column (storing the original column names) and a value column (storing the corresponding values).
- Use
var_nameandvalue_nameYou can customize the names of the new columns.
Example 2: Without value_vars - melt all columns except id_vars
When value_vars is not specified, all columns except id_vars are automatically melted.
Example
import
pandas
as
pd
1. Create data with more columns
df
=
pd.
DataFrame
(
{
'id'
:
[
1
,
2
,
3
]
,
'name'
:
[
'Alice'
,
'Bob'
,
'Charlie'
]
,
'math'
:
[
90
,
85
,
92
]
,
'english'
:
[
88
,
90
,
87
]
,
'science'
:
[
95
,
88
,
91
]
}
)
(
"=== Original data ==="
)
(
df
)
2. Specify only id_vars; all other columns are melted automatically
melted
=
pd.
melt
(
df
,
id_vars
=
[
'id'
,
'name'
]
)
(
"n=== Melt all non-id columns ==="
)
(
melted
)
3. The case of multiple id_vars
(
"n=== Multiple id_vars ==="
)
melted_multi
=
pd.
melt
(
df
,
id_vars
=
[
'name'
]
,
value_vars
=
[
'math'
,
'english'
,
'science'
]
)
(
melted_multi
)
4. Use only one id_var
(
"n=== One id_var ==="
)
melted_one
=
pd.
melt
(
df
,
id_vars
=
[
'id'
]
)
(
melted_one
)
Expected output:
=== 原始数据 ===
id name math english science
0 1 Alice 90 88 95
1 2 Bob 85 90 88
2 3 Charlie 92 87 91
=== 融化所有非id列 ===
id name variable value
0 1 Alice math 90
1 2 Bob math 85
2 3 Charlie math 92
3 1 Alice english 88
4 2 融化为两列(variable 和 value)。
- 不指定 value_vars 时,系统会自动识别并熔化除 id_vars 外的所有列
- id_vars 可以是单个列或多个列的组合
Code analysis:
- If not specified,
value_vars, all columns exceptid_varsare automatically melted. - When only id_vars is provided without value_vars, each data row produces a corresponding number of new rows based on the number of value_vars.
- This approach is very convenient when multiple columns of data need to be processed uniformly.
Example 3: No id_vars - melt all columns
When id_vars is not specified, the original data index is used as the identifier.
Example
import
pandas
as
pd
1. Create data (no explicit id column)
df
=
pd.
DataFrame
(
{
'Q1'
:
[
100
,
150
,
200
]
,
'Q2'
:
[
120
,
160
,
210
]
,
'Q3'
:
[
130
,
170
,
220
]
}
)
(
"=== Original data ==="
)
(
df
)
2. Do not specify id_vars; use the default index
melted
=
pd.
melt
(
df
)
(
"n=== No id_vars specified ==="
)
(
melted
)
3. Restore the original index
(
"n=== Reset index ==="
)
melted_with_index
=
pd.
melt
(
df
,
ignore_index
=
False
)
(
melted_with_index
)
4. Practical case: Create an identifier
df_with_id
=
pd.
DataFrame
(
{
'year'
:
[
2023
,
2023
,
2023
]
,
'Q1'
:
[
100
,
150
,
200
]
,
'Q2'
:
[
120
,
160
,
210
]
}
)
(
"n=== Original data (with year) ==="
)
(
df_with_id
)
First add year to id_vars
melted_year
=
pd.
melt
(
df_with_id
,
id_vars
=
[
'year'
]
)
(
"n=== Melt result including year ==="
)
(
melted_year
)
Expected output:
=== 原始数据 ===
Q1 Q2 Q3
0 100 120 130
1 150 160 170
2 200 210 220
=== 不指定 id_vars ===
variable value
0 Q1 100
1 Q1 150
2 融化所有列,将原始列名转为 variable 列的值,原始值转为 value 列。
Code analysis:
- When id_vars is not specified, only the variable and value columns remain.
- Use
ignore_index=FalseYou can keep the original index for easy comparison with the original data later. - In practice, you usually specify one or more id_vars to keep key information.
Example 4: Practical case - preparation before data visualization
melt() is a great helper for data visualization; many plotting libraries (such as Seaborn and Matplotlib) handle long-format data better.
Example
import
pandas
as
pd
1. Create sales data (one column per region)
sales
=
pd.
DataFrame
(
{
'product'
:
[
'A'
,
'B'
,
'C'
,
'D'
]
,
'Jan'
:
[
1200
,
1500
,
900
,
1100
]
,
'Feb'
:
[
1350
,
1600
,
950
,
1200
]
,
'Mar'
:
[
1100
,
1450
,
880
,
1050
]
}
)
(
"=== wide-format sales data ==="
)
(
sales
)
2. Melt to long format (for visualization)
sales_long
=
pd.
melt
(
sales
,
id_vars
=
[
'product'
]
,
var_name
=
'month'
,
value_name
=
'sales'
)
(
"n=== long-format sales data ==="
)
(
sales_long
)
3. Data processing example: calculate year-over-year growth
Add month numbers
month_map
=
{
'Jan'
:
1
,
'Feb'
:
2
,
'Mar'
:
3
}
sales_long
[
'month_num'
]
=
sales_long
[
'month'
]
.
map
(
month_map
)
(
"n=== add month numbers ==="
)
(
sales_long
)
4. Filter data for specific months
feb_sales
=
sales_long
[
sales_long
[
'month'
]
==
'Feb'
]
(
"n=== February sales data ==="
)
(
feb_sales
)
Expected output:
=== 宽格式销售数据 ===
product Jan Feb Mar
0 A 1200 1350 1100
product Jan 180 170 6
=== 长格式销售数据(用于可视化) ===
product month sales
0 A Jan 1200
1 B Jan 1500
2 C Jan 900
3 D Jan 1100
4 A Feb 1350
Code analysis:
- Wide-format data has one column per region/time point, making it easy to view and enter.
- Long-format data has one row per observation and is the standard format for statistical analysis.
- Visualization libraries such as Seaborn accept long-format data, making it easy to create grouped bar charts, line charts, and more.
- Use
id_varsYou can keep categorical variables such as product and region from being melted.
Example 5: melting with multi-level column indexes
When a DataFrame has a multi-level column index, you can use col_level parameter was added.
Example
import
pandas
as
pd
1. Create data with a multi-level column index
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
=
[
'Category'
,
'Quarter'
]
)
)
(
"=== Original data (multi-level column index) ==="
)
(
df
)
2. Melt all columns (without specifying a level)
(
"n=== melt all columns ==="
)
melted_all
=
pd.
melt
(
df
,
ignore_index
=
False
)
(
melted_all
)
3. Melt only the inner level (Quarter)
(
"n=== melt only the Quarter level ==="
)
melted_quarter
=
pd.
melt
(
df
,
col_level
=
1
)
(
melted_quarter
)
4. Melt only the outer level (Category)
(
"n=== melt only the Category level ==="
)
melted_category
=
pd.
melt
(
df
,
col_level
=
0
)
(
melted_category
)
Expected output:
=== 原始数据(多层列索引)===
Category Electronics Furniture
Quarter Q1 Q2 Q1 Melting different levels will produce different results:
- 融化内层(Quarter)保留 Category 作为 id
- 融化外层(Category)保留 Quarter 作为 id
Code analysis:
- For a DataFrame with a multi-level column index, column names are in tuple form: (Category, Quarter).
col_level=0Melt the outer level (Category), keeping Quarter as the id.col_level=1Melt the inner level (Quarter), keeping Category as the id.- This flexibility lets you choose which level to melt based on your analysis needs.
Tip:
pd.melt()It is a great helper for data visualization. Most plotting libraries (such as Seaborn and Plotnine) work better with long-format data, so converting the data with melt() before plotting is a common practice.
Common Pandas functions