

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
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
Built-in functions like sum and mean cover most cases, but sometimes you need a calculation that doesn't exist out-of-the-box, like a revenue range. Luckily, you can pass custom functions to .agg() using lambda functions or regular ol' named functions.
orders = pd.DataFrame(
{
"category": ["Electronics", "Electronics", "Clothing", "Clothing", "Clothing"],
"revenue": [500, 100, 200, 400, 350],
"cost": [300, 60, 100, 200, 175],
}
)
summary = orders.groupby("category").agg(
revenue_range=("revenue", lambda x: x.max() - x.min()),
)
You can also just define a regular named function, and pass it in:
def revenue_range(series):
return series.max() - series.min()
summary = orders.groupby("category").agg(
spread=("revenue", revenue_range),
)
If your lambda is longer than one line of logic, write a named function instead. Named functions are easier to test and debug.
There's nothing wrong with using custom functions and built-in ones in the same .agg() call:
summary = orders.groupby("category").agg(
total_revenue=("revenue", "sum"),
order_count=("revenue", "count"),
revenue_spread=("revenue", lambda x: x.max() - x.min()),
)
SnackStack's reliability team watches for ovens and fridges whose temperature bounces around too much.