Learn Before
Concept

Reshaping Pandas DataFrames Using the melt() Method

The Pandas melt() method unpivots a DataFrame from a wide format to a long format. It allows you to select specific columns to act as identifier variables (id_vars), while converting the remaining columns into a two-column format representing measured variables and their corresponding values.

For example, given a DataFrame:

first last height weight 0 John Doe 5.5 130 1 Mary Bo 6.0 150

Transforming the data using df.melt(id_vars=["first", "last"]) yields:

first last variable value 0 John Doe height 5.5 1 Mary Bo height 6.0 2 John Doe weight 130.0 3 Mary Bo weight 150.0

By default, the resulting DataFrame is given a new zero-based integer index. Setting ignore_index=False retains the original index values from before the melt operation.

0

1

Updated 2026-07-04

Tags

Python Programming Language

Data Science