We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Grouping by Multiple Columns

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    650

This creates one group for every unique combination of region and category. West + Electronics is a different group from East + Electronics.

Order Matters

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.

Counting Group Sizes

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            2

Assignment

SnackStack'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.