Sub topic 9
Looking inside groups
A GroupBy object is lazy. It holds the instructions for splitting a DataFrame but computes nothing until you aggregate. This chapter covers the tools for looking at the groups themselves: iterating over them, pulling one out with get_group, and checking how many groups there are and which rows belong to each.
This chapter assumes you can create a DataFrame, select columns, and read a pandas index. It also assumes you know how df.groupby("region") and a simple aggregation work from earlier chapters.
Why inspect groups
Aggregation hides the rows behind each number. Inspection helps in three situations:
- Debugging a surprising result. If a total looks wrong, look at the rows that produced it.
- Developing a custom function. Test your logic on one real group before you pass it to
applyorfilter. - Validating the split. Check that the number of groups and their keys match what you expect, especially after cleaning data.
flowchart TDReplace the above: the diagram must use the fence form below.
Iterating over groups
A GroupBy object is iterable. Each step yields a pair: the group key and a DataFrame holding that group's rows.
import pandas as pd
df = pd.DataFrame({
"region": ["North", "North", "South", "South", "South"],
"product": ["A", "B", "A", "A", "B"],
"units": [10, 5, 7, 3, 8],
"revenue": [100.0, 75.0, 70.0, 30.0, 120.0],
})
g = df.groupby("region")
for name, group in g:
print(name)
print(group)
print()
# North
# region product units revenue
# 0 North A 10 100.0
# 1 North B 5 75.0
#
# South
# region product units revenue
# 2 South A 7 70.0
# 3 South A 3 30.0
# 4 South B 8 120.0Three details matter here:
- Each group keeps the original index labels (0 and 1 for North, 2 to 4 for South). It is a slice of the original frame, not a renumbered copy.
- The grouping column is still present in each group. You can read it, but it is the same value in every row.
- Groups arrive in sorted key order by default, because
sort=True. Rows whose key is missing are skipped unless you passdropna=False.
Keys from several columns are tuples
When you group by a list of columns, each key is a tuple. Unpack it in the loop header.
for (region, product), group in df.groupby(["region", "product"]):
print(region, product, len(group))
# North A 1
# North B 1
# South A 2
# South B 1In pandas 2.0 and later, a list with one column also produces tuple keys. df.groupby(["region"]) yields ("North",) instead of "North". If code that worked on a string key breaks after an upgrade, check whether you passed a list.
Iterating over one column
If you select a column first, the iteration yields Series instead of DataFrames.
for name, revenue in df.groupby("region")["revenue"]:
print(name, revenue.tolist())
# North [100.0, 75.0]
# South [70.0, 30.0, 120.0]Collecting groups into a dictionary
A dictionary comprehension turns the groups into a lookup you can use again.
frames = {name: group for name, group in df.groupby("region")}
print(frames["North"]["units"].sum())
# 15This works well for small data. For large data, use get_group instead, or aggregate directly, because the dictionary holds a copy of every group.
Fetching one group with get_group
get_group returns the rows for a single key without a loop.
south = g.get_group("South")
print(south)
# region product units revenue
# 2 South A 7 70.0
# 3 South A 3 30.0
# 4 South B 8 120.0For a multi-column grouping, pass a tuple in the same order as the grouping columns.
pair = df.groupby(["region", "product"])
print(pair.get_group(("South", "A")))
# region product units revenue
# 2 South A 7 70.0
# 3 South A 3 30.0If you select a column before calling get_group, the result is a Series.
print(df.groupby("region")["revenue"].get_group("North"))
# 0 100.0
# 1 75.0
# Name: revenue, dtype: float64Common errors with get_group
- A key that does not exist raises
KeyError.g.get_group("East")fails because East is not a region. Check"East" in g.groupsfirst when the key comes from user input. - A tuple is required for multiple keys. Passing
"South"to the two-column grouping above fails. Pass("South", "A"). - Scalars with list groupings are deprecated. If you grouped by
["region"], pass("South",). A bare"South"raises a warning in recent versions. - Key types must match. If a key column holds integers,
get_group("1")fails andget_group(1)works.
Group metadata: ngroups, groups, indices, and size
You can also ask the GroupBy object about its structure without materializing any group.
print(g.ngroups)
# 2
print(list(g.groups))
# ['North', 'South']
print(g.indices)
# {'North': array([0, 1]), 'South': array([2, 3, 4])}
print(g.size())
# region
# North 2
# South 3
# dtype: int64| Tool | Returns | Use it for |
|---|---|---|
| `g.ngroups` | An integer | Checking how many groups the split produced |
| `g.groups` | Dict of key to index labels | Checking which labels belong to each key |
| `g.indices` | Dict of key to integer positions | Positional indexing with `iloc` |
| `g.size()` | Series of row counts | Spotting tiny or empty-looking groups |
| `g.get_group(key)` | DataFrame or Series | Looking at one group's rows |
The difference between groups and indices is easy to forget. groups holds index labels, so it works with loc. indices holds integer positions, so it works with iloc. They are identical only when the DataFrame has the default RangeIndex.
Peeking with head, nth, and cumcount
Some GroupBy methods return rows from the original frame instead of one row per group. They are useful for sampling.
print(g.head(1))
# region product units revenue
# 0 North A 10 100.0
# 2 South A 7 70.0
print(g.cumcount().tolist())
# [0, 1, 0, 1, 2]head(n) returns the first n rows of each group, in original row order. cumcount() numbers the rows inside each group starting from 0, which lets you label "first row per group" and filter on it. These methods keep the original index, so the results line up with the source DataFrame.
A debugging workflow
Iteration is the right tool for developing a function that you will later apply to every group. Pull out one group, write the logic against it, then hand the function to pandas.
first_name, first_group = next(iter(g))
def top_product(group):
return group.loc[group["revenue"].idxmax(), "product"]
print(first_name, top_product(first_group))
# North A
print(g.apply(top_product, include_groups=False))
# region
# North A
# South B
# dtype: objectThe function runs on a real group first, so any error points at your logic and not at the groupby machinery. The include_groups=False argument is available from pandas 2.2. It stops apply from passing the grouping column into the function, which avoids a deprecation warning. Remove it if you run an older version.
Groups are snapshots
The frames yielded by iteration and returned by get_group are separate objects from the original DataFrame. Assigning to one, such as group["flag"] = True, does not change df and may raise a SettingWithCopyWarning. To add group-based columns to the original, use transform, which is covered in the next chapters.
Summary of key points
- Iterating over a GroupBy yields
(key, group)pairs. Multi-column keys are tuples. get_group(key)returns a single group, and raisesKeyErrorif the key is absent.ngroups,groups,indices, andsize()describe the split without building the groups.head,nth, andcumcountgive row-level views that keep the original index.- Use inspection to debug and prototype. Use aggregation,
transform, orfilterto compute.
Exercise
Using the df from this chapter, write code that returns the rows for region "South" and product "B" and prints how many groups result from grouping by region and product. Then explain what happens if you call get_group("South") on that two-column grouping.
Show answer
Use pair = df.groupby(["region", "product"]), then pair.get_group(("South", "B")), which returns the single row at index 4 (units 8, revenue 120.0). pair.ngroups prints 4, because the data contains the combinations North/A, North/B, South/A and South/B. Calling pair.get_group("South") fails with a KeyError (or a similar error about the key) because the grouping has two keys, so each key must be a tuple such as ("South", "B").
Exercise
A DataFrame has the index labels [10, 20, 30, 40] and is grouped by a column. g.groups["x"] and g.indices["x"] are both available for the group "x", which holds the first two rows. What does each contain, and which one would you pass to iloc?
Show answer
g.groups["x"] contains the index labels 10 and 20. g.indices["x"] contains the integer positions 0 and 1. You pass indices to iloc, and groups to loc.