0
0
PandasComparisonBeginner · 3 min read

Melt vs Pivot in pandas: Key Differences and Usage

In pandas, melt transforms data from wide to long format by unpivoting columns into rows, while pivot reshapes data from long to wide format by spreading rows into columns. Use melt to normalize data and pivot to create a summary table with unique index and columns.
⚖️

Quick Comparison

This table summarizes the main differences between melt and pivot in pandas.

Aspectmeltpivot
PurposeConvert wide data to long formatConvert long data to wide format
Input shapeWide format DataFrameLong format DataFrame
Output shapeLong format DataFrameWide format DataFrame
Duplicates handlingWorks with duplicatesFails if duplicates exist in index/columns
Typical use caseNormalize data for analysisCreate summary tables or cross-tabs
Function signaturepd.melt(df, id_vars, value_vars)df.pivot(index, columns, values)
⚖️

Key Differences

melt is used to unpivot a DataFrame from wide format to long format. It takes multiple columns and turns them into two columns: one for variable names and one for values. This is helpful when you want to normalize data or prepare it for plotting or analysis.

On the other hand, pivot reshapes data from long format back to wide format by spreading unique values from one column into multiple columns. It requires a unique index/column combination; otherwise, it raises an error. This makes pivot ideal for creating summary tables or cross-tabulations.

Another difference is how they handle duplicates. melt can handle duplicates easily because it stacks data vertically. pivot cannot handle duplicates and will raise an error if the reshaping is ambiguous.

⚖️

Code Comparison

Here is an example showing how to use melt to convert a wide DataFrame into a long format.

python
import pandas as pd

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

melted = pd.melt(df, id_vars=['Name'], value_vars=['Math', 'Science'], var_name='Subject', value_name='Score')
print(melted)
Output
Name Subject Score 0 Alice Math 90 1 Bob Math 80 2 Alice Science 85 3 Bob Science 95
↔️

Pivot Equivalent

This example shows how to use pivot to convert the long format back to wide format.

python
pivoted = melted.pivot(index='Name', columns='Subject', values='Score')
print(pivoted.reset_index())
Output
Subject Name Math Science 0 Alice 90 85 1 Bob 80 95
🎯

When to Use Which

Choose melt when you need to transform wide data into a tidy long format for easier analysis or visualization. It is best for normalizing data with multiple measurement columns.

Choose pivot when you want to reshape long data into a wide format, such as creating summary tables or cross-tabulations with unique index and columns. Avoid pivot if your data has duplicates in the reshaping keys.

Key Takeaways

melt converts wide data to long format by unpivoting columns into rows.
pivot converts long data to wide format by spreading rows into columns.
melt handles duplicates easily; pivot requires unique index/columns.
Use melt for data normalization and pivot for summary tables.
Both are essential for reshaping data but serve opposite purposes.