If you’re working with reshaping data in Pandas, you’ve probably come across melt()
and pivot()
. They’re two powerful but opposite operations — and knowing when to use each is key to structuring your data efficiently.
What is pandas.melt()?
melt()
turns a wide-format DataFrame into a long-format DataFrame. It un-pivots your data so that one or more columns become row values.
Example:
import pandas as pd
df = pd.DataFrame({
'Name': ['Alice', 'Bob'],
'Math': [85, 90],
'Science': [88, 95]
})
melted = pd.melt(df, id_vars=['Name'], var_name='Subject', value_name='Score')
Output:
Name Subject Score
0 Alice Math 85
1 Bob Math 90
2 Alice Science 88
3 Bob Science 95
Use melt() when:
- You want to convert column headers into row values
- You need to prepare data for plotting or exporting
- You’re tidying messy datasets
What is pandas.pivot()?
pivot()
does the opposite — it reshapes long-format data into a wide format. You specify which column should be the index, which should be columns, and which should hold values.
Example:
data = {
'Name': ['Alice', 'Alice', 'Bob', 'Bob'],
'Subject': ['Math', 'Science', 'Math', 'Science'],
'Score': [85, 88, 90, 95]
}
df_long = pd.DataFrame(data)
pivoted = df_long.pivot(index='Name', columns='Subject', values='Score')
Output:
Subject Math Science
Name
Alice 85 88
Bob 90 95
Use pivot() when:
- You have tidy long-format data
- You want to reformat it into a wide summary table
- Your combination of index/columns is unique
Common Pitfalls
pivot()
will raise an error if duplicate index-column pairs exist- Use
pivot_table()
instead if you need aggregation or handling duplicates melt()
is very forgiving and flexible
Summary: melt() vs pivot()
Feature | melt() |
pivot() |
---|---|---|
Purpose | Convert wide → long | Convert long → wide |
Common Use | Data cleaning | Data summarization |
Flexibility | Very flexible | Less flexible |
Handles duplicates? | Yes | No (use pivot_table) |
Use melt()
to tidy and flatten your data. Use pivot()
to rebuild a summary table. These two tools give you full control over reshaping your DataFrames — once you master them, you’ll move between formats with ease.