🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpandas

pandas Documentation

LOADING ENGINE...

pd.melt()

AI & DATA SCIENCE // pd-melt

pd.melt() reshapes a DataFrame from a wide format into a long format, turning multiple columns into rows of key-value pairs.

Syntax

pd.melt(frame, id_vars=None, value_vars=None, var_name='variable', value_name='value')

Deep Dive Course

melt() is the inverse operation of pivot(): id_vars specifies which columns should stay as identifying columns, unchanged, while every other column, or a specific list given in value_vars, gets unpivoted into two new columns — one holding the original column names, var_name, 'variable' by default, and one holding the corresponding values, value_name, 'value' by default. This long format is often what plotting libraries and certain statistical/modeling tools expect, even though a wide format is usually more natural for a human to read directly.

1Understanding pd.melt()

melt() is the inverse operation of pivot(): id_vars specifies which columns should stay as identifying columns, unchanged, while every other column, or a specific list given in value_vars, gets unpivoted into two new columns — one holding the original column names, var_name, 'variable' by default, and one holding the corresponding values, value_name, 'value' by default. This long format is often what plotting libraries and certain statistical/modeling tools expect, even though a wide format is usually more natural for a human to read directly.

💡

Use melt() specifically when a plotting library or modeling tool expects one row per observation in a long format, rather than the wide, one-row-per-subject format that's usually more natural for humans to read directly.

editor.html
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "math": [90, 85], "science": [95, 80]})
print(pd.melt(df, id_vars=["name"], var_name="subject", value_name="score"))
localhost:3000

2Practical Example

Here is a real-world application of pd.melt() showing how it is used in production Pandas code.

editor.html
import pandas as pd

df = pd.DataFrame({"name": ["Alice"], "jan": [100], "feb": [150]})
long_df = pd.melt(df, id_vars=["name"])
print(long_df.shape)
localhost:3000

3Best Practices

Follow these guidelines when working with pd.melt():

1. Specify id_vars explicitly to control which columns stay fixed as identifiers, rather than relying on defaults that might unpivot columns you actually wanted to keep

2. Give var_name and value_name meaningful custom names instead of the generic defaults, for a more self-documenting result

3. Use melt() before passing data to plotting libraries that expect long-format, one-row-per-observation data

⚠️

Tip: Use melt() specifically when a plotting library or modeling tool expects one row per observation in a long format, rather than the wide, one-row-per-subject format that's usually more natural for humans to read directly.

editor.html
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "math": [90, 85], "science": [95, 80]})
print(pd.melt(df, id_vars=["name"], var_name="subject", value_name="score"))
localhost:3000

Examples

Example 01Basic Usage
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "math": [90, 85], "science": [95, 80]})
print(pd.melt(df, id_vars=["name"], var_name="subject", value_name="score"))
Example 02Advanced Example
import pandas as pd

df = pd.DataFrame({"name": ["Alice"], "jan": [100], "feb": [150]})
long_df = pd.melt(df, id_vars=["name"])
print(long_df.shape)

Best Practices

  • Specify id_vars explicitly to control which columns stay fixed as identifiers, rather than relying on defaults that might unpivot columns you actually wanted to keep
  • Give var_name and value_name meaningful custom names instead of the generic defaults, for a more self-documenting result
  • Use melt() before passing data to plotting libraries that expect long-format, one-row-per-observation data

Interview Question

Why is pd.melt() sometimes described as the inverse of pd.pivot()?

Hint: Think about what each function does to the DataFrame's shape and where the column names/values end up.

pivot() takes long-format data, where category names live as values inside a column, and reshapes it into a wide format, turning those category values into brand-new column headers, with the corresponding data filling in the cells beneath them. melt() does exactly the reverse: it takes wide-format data, where category names are the column headers, and collapses those columns back down into two long-format columns, one holding the original column names as values and one holding the corresponding data — converting column headers back into row values is precisely the inverse of the transformation pivot() performs.

Exercises

MediumPractice using pd.melt() in a real scenario.
View Solution
import pandas as pd

df = pd.DataFrame({"name": ["Alice", "Bob"], "math": [90, 85], "science": [95, 80]})
print(pd.melt(df, id_vars=["name"], var_name="subject", value_name="score"))

Frequently Asked Questions

Why is pd.melt() sometimes described as the inverse of pd.pivot()?

pivot() takes long-format data, where category names live as values inside a column, and reshapes it into a wide format, turning those category values into brand-new column headers, with the corresponding data filling in the cells beneath them. melt() does exactly the reverse: it takes wide-format data, where category names are the column headers, and collapses those columns back down into two long-format columns, one holding the original column names as values and one holding the corresponding data — converting column headers back into row values is precisely the inverse of the transformation pivot() performs.

Related Functions

df-pivotpd-pivot-tabledf-stack