How to Use melt in pandas: Simple Guide with Examples
Use
pandas.melt() to transform a DataFrame from wide format to long format by unpivoting selected columns into rows. Specify id_vars to keep columns fixed and value_vars to select columns to unpivot. This helps in data analysis and visualization by making data tidy.Syntax
The pandas.melt() function has this basic syntax:
frame: The DataFrame to reshape.id_vars: Columns to keep fixed (not unpivoted).value_vars: Columns to unpivot into rows (optional, defaults to all columns not inid_vars).var_name: Name for the new variable column (optional).value_name: Name for the new value column (optional).
python
pandas.melt(frame, id_vars=None, value_vars=None, var_name=None, value_name='value', col_level=None, ignore_index=True)
Example
This example shows how to convert a wide DataFrame with sales data for different years into a long format using melt(). It keeps the Product column fixed and unpivots the year columns.
python
import pandas as pd data = { 'Product': ['A', 'B', 'C'], '2019': [100, 150, 200], '2020': [110, 160, 210], '2021': [120, 170, 220] } df = pd.DataFrame(data) melted = pd.melt(df, id_vars=['Product'], var_name='Year', value_name='Sales') print(melted)
Output
Product Year Sales
0 A 2019 100
1 B 2019 150
2 C 2019 200
3 A 2020 110
4 B 2020 160
5 C 2020 210
6 A 2021 120
7 B 2021 170
8 C 2021 220
Common Pitfalls
Common mistakes when using melt() include:
- Not specifying
id_vars, which can cause unexpected columns to be unpivoted. - Forgetting to set
var_nameorvalue_name, leading to unclear column names. - Trying to melt columns with mixed data types without cleaning first.
Here is an example of a wrong and right way:
python
import pandas as pd data = {'Name': ['John', 'Anna'], 'Math': [90, 95], 'Science': [85, 88]} df = pd.DataFrame(data) # Wrong: Not specifying id_vars (Name will be unpivoted too) wrong = pd.melt(df) # Right: Specify id_vars to keep 'Name' fixed right = pd.melt(df, id_vars=['Name'], var_name='Subject', value_name='Score') print('Wrong melt output:\n', wrong) print('\nRight melt output:\n', right)
Output
Wrong melt output:
variable value
0 Name John
1 Name Anna
2 Math 90
3 Math 95
4 Science 85
5 Science 88
Right melt output:
Name Subject Score
0 John Math 90
1 Anna Math 95
2 John Science 85
3 Anna Science 88
Quick Reference
Remember these tips when using melt():
- Use
id_varsto keep columns fixed. - Use
value_varsto select columns to unpivot. - Set
var_nameandvalue_namefor clear column names. - Check data types before melting to avoid errors.
Key Takeaways
Use pandas.melt() to reshape data from wide to long format by unpivoting columns.
Always specify id_vars to keep certain columns fixed during melting.
Set var_name and value_name for meaningful column names in the output.
Check your data types before melting to avoid unexpected results.
Melted data is easier to analyze and visualize in many cases.