Predict the Pivot Table Shape
Advanced · Predict the output · 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 lessonWhat will this code print? Think about how many unique values exist in the index and columns.
import pandas as pd
df = pd.DataFrame({
'color': ['red', 'blue', 'red', 'blue', 'green'],
'size': ['S', 'S', 'M', 'M', 'S'],
'count': [1, 2, 3, 4, 5]
})
pivot = pd.pivot_table(df, index='color', columns='size', values='count', aggfunc='sum', fill_value=0)
print(pivot.shape)# Type the exact output
More Pandas Pivot Table exercises
- Create a Sales Pivot TableIntermediate
- Add Totals with MarginsAdvanced
- Create a Cross-TabulationAdvanced
- Unpivot with melt()Advanced
All Python exercises · 50 practice problems · Data Science & Machine Learning quiz