Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.melt() function

Pandas pd.melt() function

Pandas Common Functions Common Pandas functions


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

- Type: DataFrame. - Description: **Required parameter**. The source DataFrame, i.e., the data to convert from wide to long format. - 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. - 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. - Type: string or None. - Description: The name of the generated column for storing the original column names. Defaults to 'variable'. - Type: string. - Description: The name of the generated value column. Defaults to 'value'. - Type: int, str, or None. - Description: If the columns are a MultiIndex, specify the level(s) to melt.

Function description


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

]

}

)

print

(

"=== Original wide-format data ==="

)

print

(

df

)

2. Convert to long format using pd.melt()

melted

=

pd.

melt

(

df

,

id_vars

=

[

'name'

]

,

value_vars

=

[

'Q1_sales'

,

'Q2_sales'

,

'Q3_sales'

]

)

print

(

"n=== pd.melt() convert to long format ==="

)

print

(

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'

)

print

(

"n=== Custom column names ==="

)

print

(

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:

  1. The original data is in wide format, with one person per row, and Q1, Q2, Q3 are the sales data columns for three quarters.
  2. id_vars=['name'] Specify the name column to remain unchanged as the identifier.
  3. value_vars=['Q1_sales', 'Q2_sales', 'Q3_sales'] Specify the columns to melt.
  4. The result adds a variable column (storing the original column names) and a value column (storing the corresponding values).
  5. Use var_name and value_name You 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

]

}

)

print

(

"=== Original data ==="

)

print

(

df

)

2. Specify only id_vars; all other columns are melted automatically

melted

=

pd.

melt

(

df

,

id_vars

=

[

'id'

,

'name'

]

)

print

(

"n=== Melt all non-id columns ==="

)

print

(

melted

)

3. The case of multiple id_vars

print

(

"n=== Multiple id_vars ==="

)

melted_multi

=

pd.

melt

(

df

,

id_vars

=

[

'name'

]

,

value_vars

=

[

'math'

,

'english'

,

'science'

]

)

print

(

melted_multi

)

4. Use only one id_var

print

(

"n=== One id_var ==="

)

melted_one

=

pd.

melt

(

df

,

id_vars

=

[

'id'

]

)

print

(

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:

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

]

}

)

print

(

"=== Original data ==="

)

print

(

df

)

2. Do not specify id_vars; use the default index

melted

=

pd.

melt

(

df

)

print

(

"n=== No id_vars specified ==="

)

print

(

melted

)

3. Restore the original index

print

(

"n=== Reset index ==="

)

melted_with_index

=

pd.

melt

(

df

,

ignore_index

=

False

)

print

(

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

]

}

)

print

(

"n=== Original data (with year) ==="

)

print

(

df_with_id

)

First add year to id_vars

melted_year

=

pd.

melt

(

df_with_id

,

id_vars

=

[

'year'

]

)

print

(

"n=== Melt result including year ==="

)

print

(

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:

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

]

}

)

print

(

"=== wide-format sales data ==="

)

print

(

sales

)

2. Melt to long format (for visualization)

sales_long

=

pd.

melt

(

    sales

,

    id_vars

=

[

'product'

]

,

    var_name

=

'month'

,

    value_name

=

'sales'

)

print

(

"n=== long-format sales data ==="

)

print

(

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

)

print

(

"n=== add month numbers ==="

)

print

(

sales_long

)

4. Filter data for specific months

feb_sales

=

sales_long

[

sales_long

[

'month'

]

==

'Feb'

]

print

(

"n=== February sales data ==="

)

print

(

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:

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'

]

)

)

print

(

"=== Original data (multi-level column index) ==="

)

print

(

df

)

2. Melt all columns (without specifying a level)

print

(

"n=== melt all columns ==="

)

melted_all

=

pd.

melt

(

df

,

ignore_index

=

False

)

print

(

melted_all

)

3. Melt only the inner level (Quarter)

print

(

"n=== melt only the Quarter level ==="

)

melted_quarter

=

pd.

melt

(

df

,

col_level

=

1

)

print

(

melted_quarter

)

4. Melt only the outer level (Category)

print

(

"n=== melt only the Category level ==="

)

melted_category

=

pd.

melt

(

df

,

col_level

=

0

)

print

(

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:

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.

Pandas Common Functions Common Pandas functions