Sub topic 11
Aggregating by group with groupby
This chapter assumes you can create a DataFrame, select columns, and tell a Series from a DataFrame. It uses the same sales table as the earlier chapters.
The split-apply-combine model
groupby does not compute anything by itself. It splits the rows into groups by the values in one or more columns. You then apply a reduction such as sum to each group, and pandas combines the results into one object.
A first grouped sum
import pandas as pd
df = pd.DataFrame({
"region": ["North", "South", "North", "East", "South", "East"],
"product": ["A", "B", "B", "A", "A", "B"],
"units": [10, 5, None, 8, 12, 7],
"price": [2.5, 4.0, 4.0, 2.5, 2.5, 4.0],
})
totals = df.groupby("region")["units"].sum()
print(totals)
print(totals.index.name)Selecting ["units"] after groupby limits the work to that column. The result is a Series. Its index holds the group keys, which pandas sorts alphabetically by default, so the order is East, North, South. The totals are 15.0, 10.0 and 17.0. They are floats because the column contains a missing value.
If you prefer a regular column over an index, pass as_index=False or call reset_index():
flat = df.groupby("region", as_index=False)["units"].sum()
print(flat)This returns a DataFrame with region and units columns, which is easier to merge or plot.
Common reductions
Frequently used reductions on a group are sum, mean, median, min, max, count and size. Two of them are easy to confuse:
| Method | What it counts |
|---|---|
| `size()` | All rows in each group, including rows with missing values |
| `count()` | Only non-missing values in the selected column |
print(df.groupby("region").size())
print(df.groupby("region")["units"].count())The first call returns 2 for every region. The second returns 2 for East, 1 for North and 2 for South, because one North row has no units value.
Grouping by several columns
Pass a list to group by combinations of keys. The result has a MultiIndex, with one level per key.
by_both = df.groupby(["region", "product"])["units"].sum()
print(by_both)Every combination that appears in the data gets a row. North with product B has only a missing value, and pandas reports its sum as 0.0, not as missing. That is the default of sum. If you need a missing result in that case, use sum(min_count=1).
Common mistakes
- Calling
df.groupby("region").mean()on a table with text columns. In current pandas this raises aTypeErrorfor non-numeric columns. Select the numeric columns first, or passnumeric_only=True. - Expecting the result to be sorted by value. Groups are sorted by key. Sorting by value is a separate step, covered later.
- Forgetting that the result of a single-column selection is a Series, not a DataFrame. Use
["units"]for a Series and[["units"]]for a one-column DataFrame.
Exercise
Using the df above, what does df.groupby("product")["units"].size() return for product A, and how does it differ from .count()?
Show answer
Product A has three rows (North, East, South), so size() returns 3. All three have units values (10, 8 and 12), so count() also returns 3. For product B, size() returns 3 but count() returns 2, because the North row has a missing value in units.