Unpivot with melt()
Advanced · Write the code · from Pandas Pivot Tables and Cross-Tabulation for Business Analysis
From the lesson: Pandas Pivot Tables and Cross-Tabulation for Business Analysis
If you have ever used a pivot table in Excel or Google Sheets, you already understand the core idea. You take a flat table of raw data and reshape it into a summary that shows one variable along the rows, another along the columns, and computed values (sums, averages, counts) in the cells.
Read the lessonUse pd.melt() to convert the wide DataFrame into long format. Keep name as the identifier column. The melted variable column should be called subject and the value column should be called score.
Print the result using .to_string(index=False).
import pandas as pd
df = pd.DataFrame({
'name': ['Alice', 'Bob'],
'math': [90, 80],
'science': [85, 95]
})
# Melt to long format
More Pandas Pivot Table exercises
- Create a Sales Pivot TableIntermediate
- Add Totals with MarginsAdvanced
- Create a Cross-TabulationAdvanced
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz