0
0
Pandasdata~5 mins

melt() for unpivoting in Pandas

Choose your learning style9 modes available
Introduction

We use melt() to turn wide data into long data. This helps us see data in a simpler, tidy format.

You have a table with many columns for similar data and want to combine them into one column.
You want to prepare data for charts that need long format, like line plots.
You want to make it easier to filter or group data by a variable that is spread across columns.
You want to clean data before analysis or machine learning where long format is preferred.
Syntax
Pandas
pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None, ignore_index=True)

frame is your DataFrame.

id_vars are columns to keep as identifiers (not unpivoted).

Examples
Unpivot all columns into two columns: variable and value.
Pandas
pd.melt(df)
Keep 'Name' column fixed, unpivot the rest.
Pandas
pd.melt(df, id_vars=['Name'])
Rename the new columns to 'Year' and 'Score' for clarity.
Pandas
pd.melt(df, id_vars=['Name'], var_name='Year', value_name='Score')
Sample Program

This code creates a table with student names and their scores in two subjects. Then it uses melt() to turn the subject columns into one column, making the data longer and easier to analyze.

Pandas
import pandas as pd

data = {
    'Name': ['Alice', 'Bob'],
    'Math': [90, 80],
    'Science': [85, 88]
}
df = pd.DataFrame(data)

print('Original DataFrame:')
print(df)

melted = pd.melt(df, id_vars=['Name'], var_name='Subject', value_name='Score')

print('\nMelted DataFrame:')
print(melted)
OutputSuccess
Important Notes

If you don't set id_vars, all columns become variables and values, which may not be what you want.

Use var_name and value_name to give meaningful names to the new columns.

Summary

melt() changes wide data into long data.

Keep some columns fixed with id_vars.

Rename new columns with var_name and value_name for clarity.