

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 4
click for more info
Not enough gems
Cost: 6 gems
1: Aggregation
incomplete
2: Grouping With Dictionaries
incomplete
3: Grouping in Pandas
incomplete
4: Category Type
incomplete
5: Grouping by Multiple Columns
incomplete
6: Multiple Aggregations
incomplete
7: Named Aggregations
incomplete
8: Custom Aggregations
incomplete
9: Pivot Tables
incomplete
10: Pivot Table Aggregations
incomplete
11: Star Schema
incomplete
12: Grain Validation
incomplete
13: Fixing Grain Violations
incomplete
14: Building a Data Model
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
A pivot table reshapes data from long format (many rows, few columns) to wide format (fewer rows, more columns). Think of it as a groupby that spreads one column's values into new columns.
Pivot tables are often exactly what you want in a report or dashboard – they map 1:1 to what stakeholders expect to see.
In long format, every observation is a row:
| team | priority | response_minutes |
|---|---|---|
| Support | high | 45 |
| Support | low | 12 |
| Billing | high | 60 |
| Billing | low | 20 |
In wide format, categories become columns:
| team | high | low |
|---|---|---|
| Support | 45 | 12 |
| Billing | 60 | 20 |
Use pd.pivot_table():
tickets = pd.DataFrame(
{
"team": ["Support", "Support", "Billing", "Billing", "Support", "Billing"],
"priority": ["high", "low", "high", "low", "high", "low"],
"response_minutes": [45, 12, 60, 20, 30, 25],
}
)
pivot = pd.pivot_table(
tickets,
values="response_minutes",
index="team",
columns="priority",
aggfunc="mean",
)
Pivot for presentation, but keep long format for computation. Long format is usually easier to work with for further analysis.
If some group combinations don't exist, you'll get NaN. Use fill_value to replace missing combinations:
pivot = pd.pivot_table(
tickets,
values="response_minutes",
index="team",
columns="priority",
aggfunc="mean",
fill_value=0,
)
SnackStack's operations team wants an energy dashboard: total power draw for every region, broken out by device type.
Complete the energy_grid_by_region_and_type function. It accepts a df of telemetry rows with region, device_type, and energy_kwh columns, and returns a pivot table.