Melt vs Pivot in pandas: Key Differences and Usage
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.
| Aspect | melt | pivot |
|---|---|---|
| Purpose | Convert wide data to long format | Convert long data to wide format |
| Input shape | Wide format DataFrame | Long format DataFrame |
| Output shape | Long format DataFrame | Wide format DataFrame |
| Duplicates handling | Works with duplicates | Fails if duplicates exist in index/columns |
| Typical use case | Normalize data for analysis | Create summary tables or cross-tabs |
| Function signature | pd.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.
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)
Pivot Equivalent
This example shows how to use pivot to convert the long format back to wide format.
pivoted = melted.pivot(index='Name', columns='Subject', values='Score') print(pivoted.reset_index())
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.melt for data normalization and pivot for summary tables.