0
0
Data Analysis Pythondata~5 mins

Melt for wide-to-long reshaping in Data Analysis Python

Choose your learning style9 modes available
Introduction

Melt helps change data from wide format to long format. This makes it easier to analyze and plot data.

You have survey data with one row per person and many columns for answers, and want one row per answer.
You want to combine multiple columns of monthly sales into one column with month names and sales values.
You need to prepare data for a chart that requires long format, like a line plot over time.
You want to stack several related columns into two columns: one for variable names and one for values.
Syntax
Data Analysis Python
pd.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value')

frame is your original DataFrame.

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

Examples
Melt all columns into two columns: variable and value.
Data Analysis Python
pd.melt(df)
Keep 'Name' column fixed, melt the rest.
Data Analysis Python
pd.melt(df, id_vars=['Name'])
Melt only 'Math' and 'Science' columns, rename columns to 'Subject' and 'Score'.
Data Analysis Python
pd.melt(df, id_vars=['Name'], value_vars=['Math', 'Science'], var_name='Subject', value_name='Score')
Sample Program

This code creates a small table with student names and scores in Math and Science. Then it melts the scores into a long format with columns 'Name', 'Subject', and 'Score'.

Data Analysis Python
import pandas as pd

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

melted = pd.melt(df, id_vars=['Name'], value_vars=['Math', 'Science'], var_name='Subject', value_name='Score')
print(melted)
OutputSuccess
Important Notes

If you don't specify id_vars, all columns are melted into variable and value columns.

Melted data is useful for plotting libraries like seaborn that expect long format.

Summary

Melt changes wide data to long data by stacking columns.

Use id_vars to keep columns fixed.

Rename variable and value columns with var_name and value_name.