Sub topic 3
Looking Inside pandas Groups
Assume you know basic Python functions, pandas DataFrames, Series, and indexes. This chapter focuses on choosing the right group-wise operation and checking what each group contains.
Inspecting groups
groupby creates a GroupBy object. It stores the grouping rules and lets you apply an operation later.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South"],
"product": ["A", "B", "A", "B"],
"revenue": [100, 75, 70, 120],
})
for region, group in df.groupby("region", sort=False):
print(region)
print(group)
north = df.groupby("region").get_group("North")
print(north)Iteration is useful for inspection. get_group retrieves one known group.
Values on every row with transform
Use transform when a group result must align with the original rows. For example, this adds each row’s regional total:
df["region_total"] = (
df["revenue"]
/ df.groupby("region")["revenue"].transform("sum")
)Each group’s shares sum to 1. Unlike agg, transform returns one value for every input row.
Keeping groups with filter
Use filter when the decision applies to a whole group:
large = df.groupby("region").filter(
lambda group: group["revenue"].sum() > 150
)Every row from a qualifying region remains. Other groups disappear.
Custom logic with apply
Use apply for logic that built-in aggregations, transform, or filter cannot express:
leaders = df.groupby("region").apply(
lambda group: group.loc[group["revenue"].idxmax()]
)apply is flexible, but often slower because pandas calls Python code for each group.
Time and categorical keys
pd.Grouper groups datetimes into periods:
monthly = df.assign(
date=pd.to_datetime(["2024-01-05", "2024-01-20", "2024-02-03", "2024-02-15"])
).groupby(pd.Grouper(key="date", freq="MS"))["revenue"].sum()For categorical keys, observed=True returns only category combinations present in the data. This avoids empty combinations when grouping by multiple categorical columns.
Pitfalls and performance
| Need | Prefer |
|---|---|
| Summary per group | `agg` |
| Value aligned to each row | `transform` |
| Keep complete groups | `filter` |
| Irregular custom output | `apply` |
Prefer vectorized built-in operations over row-wise apply. Check missing keys and category settings before trusting totals.
> callout note > Inspect a few groups before writing complex group-wise logic. It often reveals missing keys, unexpected categories, or the wrong output shape.
Exercise
Which operation should you use to add each row's group's mean value to the original DataFrame?
Show answer
Use transform, such as df.groupby("region")["revenue"].transform("mean").