Sub topic 9
Looking inside groups
This chapter assumes you can build a DataFrame, select columns, and have met df.groupby(...) and a basic aggregation. A GroupBy object is lazy. It records how to split the rows but computes nothing until you aggregate. Before you aggregate, you can look at the groups themselves.
Why inspect groups
Inspection helps in three situations:
- You want to confirm that the keys split the data the way you expected.
- A group gives a surprising aggregate and you want to see its rows.
- You need to debug a custom function before passing it to
apply.
The sample data
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")
print(g.ngroups)
print(list(g.groups))
# 2
# ['North', 'South']ngroups is the number of groups. groups is a dictionary that maps each key to the index labels of its rows. Listing it gives you the keys.
Iterating over groups
Iterating over a GroupBy object yields (key, sub-DataFrame) pairs. Each sub-DataFrame holds the full rows for that key.
for region, group in g:
print(region, len(group), group["revenue"].max())
# North 2 100.0
# South 3 120.0Fetching one group with get_group
When you need a single group, get_group returns it without a loop.
print(g.get_group("South"))
# region product units revenue
# 2 South A 7 70.0
# 3 South A 3 30.0
# 4 South B 8 120.0An unknown key raises KeyError. Check key in g.groups first if the key comes from user input.
Groups with several keys
With two or more grouping columns, each key is a tuple. Pass a tuple to get_group as well.
g2 = df.groupby(["region", "product"])
for (region, product), group in g2:
print(region, product, group["units"].sum())
# North A 10
# North B 5
# South A 10
# South B 8
print(g2.get_group(("South", "A")))
# region product units revenue
# 2 South A 7 70.0
# 3 South A 3 30.0In pandas 2.x, grouping by a list that holds one column, such as df.groupby(["region"]), also gives tuple keys of length 1. A list with a single key therefore needs for (region,), group in ..., and get_group needs ("North",). Plain df.groupby("region") gives scalar keys.
Peeking at positions
To see the first rows of every group, use head or nth-style methods on the GroupBy object. These return rows from the original DataFrame, not a summary.
print(g.head(1))
# region product units revenue
# 0 North A 10 100.0
# 2 South A 7 70.0Exercise
With g = df.groupby("region"), how would you print the number of rows in each region using a loop, and what does the key look like if you group by ["region", "product"] instead?
Show answer
Use for region, group in g: print(region, len(group)). This prints North 2 and South 3. With ["region", "product"] each key is a tuple such as ("South", "A"), so the loop unpacks it as for (region, product), group in ....