Sub topic 11
Aggregating by group with groupby
This chapter covers how groupby splits a DataFrame into groups, applies a reduction to each group, and combines the results. It assumes you know basic Python syntax, how to create a DataFrame and select columns, and the difference between a Series and a DataFrame.
All examples use the sales DataFrame from earlier chapters.
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],
})The split-apply-combine model
A groupby call does three things:
- Split. pandas divides the rows into groups that share the same key value.
- Apply. A function such as
sumormeanruns on each group separately. - Combine. The per-group results are assembled into a new Series or DataFrame.
A first grouped aggregation
Call groupby with the column to group by, select the column to summarise, and call a reduction.
totals = df.groupby("region")["units"].sum()
print(totals)The output is a Series. Its index holds the group keys, and the keys are sorted alphabetically by default:
region
East 15.0
North 10.0
South 17.0
Name: units, dtype: float64The groupby call alone computes nothing. It returns a DataFrameGroupBy object that remembers how to split the data. The work happens when you call a reduction on it. You can inspect the object to see the groups:
grouped = df.groupby("region")
print(grouped.ngroups)
print(grouped.groups)
print(grouped.get_group("North"))ngroups is the number of groups. groups maps each key to the row labels in that group. get_group returns the sub-DataFrame for one key.
Common reductions
These methods work on a grouped object and on a column selected from it.
| Method | Result per group |
|---|---|
| `sum()` | Total of the non-missing values |
| `mean()` | Average of the non-missing values |
| `median()` | Middle value |
| `min()`, `max()` | Smallest and largest value |
| `count()` | Number of non-missing values |
| `size()` | Number of rows, including those with missing values |
| `nunique()` | Number of distinct values |
| `first()`, `last()` | First or last non-missing value in the group |
The difference between count and size matters. In the North group, units has two rows but one missing value:
print(df.groupby("region")["units"].count())
print(df.groupby("region").size())count reports 1 for North, because it skips the missing value. size reports 2, because it counts rows.
Grouping by several columns
Pass a list to group by combinations of keys. The result has a MultiIndex, which is an index with one level per key.
by_both = df.groupby(["region", "product"])["units"].sum()
print(by_both)Each row of the output is one (region, product) pair that occurs in the data. Pairs that never occur do not appear. pivot_table, covered in a later chapter, fills such gaps.
To turn the index levels back into ordinary columns, use as_index=False or call reset_index() afterwards:
flat = df.groupby(["region", "product"], as_index=False)["units"].sum()
print(flat)Both approaches give a flat table. as_index=False is shorter. reset_index() is more flexible when you have already built the result.
Aggregating several columns at once
Calling a reduction directly on the grouped DataFrame applies it to every column it can handle:
print(df.groupby("region")[["units", "price"]].mean())Select the columns explicitly, as above. If you omit the selection, pandas tries to apply the reduction to every non-key column, including text columns. For a method such as mean, a text column raises a TypeError in current pandas versions. Listing the columns you want avoids that error and makes the code easier to read.
To apply different reductions to different columns, pass a dictionary to agg:
print(df.groupby("region").agg({"units": "sum", "price": "mean"}))The dictionary keys are column names and the values are reduction names. You can also pass a list of names for one column, such as {"units": ["sum", "max"]}. That produces a column MultiIndex, which is awkward to work with. The next chapter shows named aggregation, which avoids it.
Group keys and missing values
Rows whose key is missing are dropped from the result by default. Consider a copy of the data with one missing region:
df2 = df.copy()
df2.loc[0, "region"] = None
print(df2.groupby("region")["units"].sum())
print(df2.groupby("region", dropna=False)["units"].sum())The first call omits row 0 entirely. The second call, with dropna=False, adds a group labelled NaN. Use dropna=False when silently losing rows would hide a data problem. A later chapter covers missing values inside the aggregated columns.
Group order and sorting
By default groupby sorts the keys, so the output index is in ascending key order. That is not the same as sorting by the computed values. To order a result by its totals, call sort_values on it:
print(df.groupby("region")["units"].sum().sort_values(ascending=False))If you do not need sorted keys and want slightly faster grouping on large data, pass sort=False. The groups then appear in the order they first occur in the data:
print(df.groupby("region", sort=False)["units"].sum())For the sales data this returns North, South, East.
Grouping by something other than a column
The key does not have to be a column name. You can group by:
- A Series of the same length as the DataFrame.
- An index level, with
level=. - A function, which is applied to each index label.
Grouping by a computed Series is useful for bucketing:
size_band = df["units"].gt(8).map({True: "large", False: "small"})
print(df.groupby(size_band)["price"].mean())Here the rows are grouped by whether units exceeds 8. The comparison gt(8) returns False for the missing value, so that row lands in the "small" group. Check how a condition treats missing values before using it as a key.
Iterating over groups
You can loop over a grouped object. Each step yields the key and the sub-DataFrame:
for name, part in df.groupby("region"):
print(name, len(part))Looping is good for inspection and for work that does not vectorise. For ordinary summaries, prefer the built-in reductions. They run in compiled code and are much faster than a Python loop over many groups.
Common errors
- Forgetting the reduction. Printing
df.groupby("region")shows only an object description. Add.sum(),.mean()or.agg(...). - Expecting a DataFrame and getting a Series.
df.groupby("region")["units"].sum()returns a Series because you selected one column with single brackets. Use double brackets,[["units"]], to keep a DataFrame. - Reducing text columns. Applying
sumormeanto every column fails or gives meaningless results when text columns are present. Select the numeric columns first. - Using
countwhen you meantsize.countignores missing values.sizedoes not. - Losing rows with missing keys. The default
dropna=Trueremoves them without a warning. - Assuming sorted by value. Sorted keys are not sorted totals.
Exercises
Exercise
Using the sales DataFrame, write code that returns the number of non-missing units values and the number of rows for each region. Which region shows different numbers for the two, and why?
Show answer
Use df.groupby("region")["units"].count() and df.groupby("region").size(). North shows 1 non-missing value but 2 rows, because one of its two units values is missing. count skips missing values and size counts every row.
Exercise
Write one line that gives the mean price for each (region, product) pair as a flat DataFrame with ordinary columns, not a MultiIndex.
Show answer
df.groupby(["region", "product"], as_index=False)["price"].mean(). The as_index=False argument keeps the group keys as columns. Calling .reset_index() on the result of the version without it gives the same table.
Exercise
Write a line that returns the total units per region, ordered from the region with the most units to the region with the fewest.
Show answer
df.groupby("region")["units"].sum().sort_values(ascending=False). The groupby sorts the keys alphabetically, so the extra sort_values call is needed to order by the totals. The result is South (17.0), East (15.0), North (10.0).