Sub topic 3
Choosing grouping keys
This chapter assumes you can build a DataFrame, select columns, and read a pandas index. It also assumes you know that groupby splits rows into groups, applies a function to each group, and combines the results.
What counts as a key
The key tells pandas which group each row belongs to. Rows with equal key values land in the same group. A key can be a column name, a list of column names, an index level, or a Series or array of labels that you compute yourself.
All examples use this DataFrame:
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],
})Several columns
Pass a list to group by combinations of values. The result has a MultiIndex with one level per key, in the order you listed them.
print(df.groupby(["region", "product"])["revenue"].sum())
# region product
# North A 100.0
# B 75.0
# South A 100.0
# B 120.0
# Name: revenue, dtype: float64Only combinations that occur in the data appear. There is no row for a pair that never occurs.
Index levels
If the keys are already in the index, use level= instead of a column name. It accepts a level name or a position.
indexed = df.set_index(["region", "product"])
print(indexed.groupby(level="region")["revenue"].sum())
# region
# North 175.0
# South 220.0
# Name: revenue, dtype: float64Pass a list such as level=["region", "product"] to group by several levels.
Computed keys
A key does not have to exist as a column. You can pass a Series, and pandas aligns it to the DataFrame by index label, not by position. A boolean Series gives you a two-group split:
big_sale = df["revenue"].ge(80).rename("big_sale")
print(df.groupby(big_sale)["units"].sum())
# big_sale
# False 15
# True 18
# Name: units, dtype: int64Naming the Series with rename makes the result index readable. A NumPy array or plain list of the same length also works, but it carries no label.
The same idea covers two other forms:
- A function, such as
df.groupby(lambda label: label % 2), is called on each index label. - A dict or Series that maps index labels to group names, such as
df.groupby({0: "x", 1: "x", 2: "y", 3: "y", 4: "y"}), assigns groups by label. Labels missing from the mapping get a missing key and are dropped.
Choosing between them
| Situation | Key to use |
|---|---|
| The category is already a column | The column name |
| You need combinations of categories | A list of column names |
| The categories live in the index | `level=` |
| The category must be derived (a threshold, a bucket, a mapping) | A computed Series |
Computing the key and passing it directly is usually better than adding a helper column. It leaves the DataFrame unchanged. Add the column only if you need the key again later.
Common errors
- A Series key with a different index. Labels are matched, not positions. If you sort or filter the DataFrame but not the key, rows get the wrong group or a missing one. Build the key from the same DataFrame, as above.
- Mixing up key order.
["region", "product"]and["product", "region"]give the same groups but a different MultiIndex order. - Expecting a column after grouping. Key columns move into the index. The next chapters cover
as_indexandreset_indexfor changing that.
Exercise
Using the DataFrame above, how would you total units for each product within each region while keeping region as the outer index level, and what happens if you swap the key order?
Show answer
Use df.groupby(["region", "product"])["units"].sum(). Each (region, product) pair becomes one group, with region as the outer level. Swapping the order to ["product", "region"] produces the same groups and totals, but product becomes the outer level.