

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
Sometimes one grouping column isn't enough. If you group only by region, you can answer:
"How much revenue did each region generate?"
But if you group by region and category, you can answer:
"How much revenue did each product category generate in each region?"
Pass a list of column names to groupby() to group by more than one column.
orders = pd.DataFrame(
{
"region": ["West", "East", "West", "East", "West"],
"category": [
"Electronics",
"Electronics",
"Clothing",
"Clothing",
"Electronics",
],
"revenue": [500, 300, 200, 400, 150],
}
)
revenue_by_region_category = orders.groupby(["region", "category"])["revenue"].sum()
print(revenue_by_region_category)
# region category
# East Clothing 400
# Electronics 300
# West Clothing 200
# Electronics 650This creates one group for every unique combination of region and category. West + Electronics is a different group from East + Electronics.
The order of the columns controls the order of the grouped result:
orders.groupby(["category", "region"])["revenue"].sum()I recommend starting with a single groupby column. Get the result you expect, then add more columns. Debugging a multi-column groupby all at once is painful.
The .size() method counts the rows in each group. It returns a Series indexed by the group keys, so to get back to a tidy DataFrame, reset the index. The name parameter labels the new column of counts:
counts = orders.groupby(["region", "category"]).size().reset_index(name="order_count")
print(counts)
# region category order_count
# 0 East Clothing 1
# 1 East Electronics 1
# 2 West Clothing 1
# 3 West Electronics 2SnackStack's operations team wants to know how "chatty" each kind of device is in each region, so they can spot which fleets are flooding the pipeline with readings.
Complete the count_readings_by_region_and_type function. It accepts a DataFrame of device readings (with region, device_type, and device_id columns) and returns one row per region/device-type combination with a count of its readings.