Sub topic 3
Choosing grouping keys
A grouping key tells pandas how to assign each row to a group. Every groupby call depends on this choice, and most surprising results trace back to it. This chapter covers the forms a key can take and how each one shapes the result.
It assumes you can create a DataFrame, select columns with brackets, and read a Series with its index. It also assumes you know the split-apply-combine idea from the earlier chapters.
What counts as a key
The first argument to groupby is called by. It accepts several forms:
| Form of `by` | Example | How rows are assigned to groups |
|---|---|---|
| A column name | `df.groupby("region")` | Rows with equal values in that column share a group |
| A list of column names | `df.groupby(["region", "product"])` | Rows with equal value combinations share a group |
| An index level | `df.groupby(level="region")` | Rows with equal index labels at that level share a group |
| A Series or array | `df.groupby(df["units"] > 5)` | Each row gets the key at the same position or index label |
| A dict or Series mapping labels | `s.groupby({"North": "Domestic"})` | Each index label is translated to a group name |
| A mixed list | `df.groupby(["region", df["units"] > 5])` | Column names and computed keys can be combined |
Whatever form you pick, pandas ends up with one label per row. Rows with the same label go into the same group.
Grouping by one column
The examples below share this DataFrame. Define it once and reuse it.
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],
})
print(df.groupby("region")[["units", "revenue"]].sum())
# units revenue
# region
# North 15 175.0
# South 18 220.0The key column is not in the output as a column. It becomes the index of the result. Selecting [["units", "revenue"]] after groupby limits the aggregation to those columns.
A one-element list such as df.groupby(["region"]) gives the same sums. The difference shows up when you iterate over the groups or call get_group. In pandas 2.x, a one-element list produces keys that are one-element tuples, while a plain string produces scalar keys. Choose one style and use it consistently.
Grouping by several columns
Pass a list to get one group per distinct combination of values.
by_two = df.groupby(["region", "product"])["revenue"].sum()
print(by_two)
# region product
# North A 100.0
# B 75.0
# South A 100.0
# B 120.0
# Name: revenue, dtype: float64
print(df.groupby(["region", "product"]).ngroups)
# 4Three details matter here.
- The result has a MultiIndex, one level per key, in the order you listed the keys.
- The order of keys sets the order of the levels.
["product", "region"]gives the same sums but nests them the other way. - Only combinations that occur in the data become groups. If South never sold product C, there is no
(South, C)row. The chapter on categorical keys covers how to change that.
Use ngroups to check how many groups a key produces before aggregating. If you expected 4 and see 5,000, the key is probably too fine-grained. An example is a timestamp column used where a date was intended.
Grouping by index levels
When the labels you want to group by are already in the index, use level instead of moving them back into columns.
indexed = df.set_index(["region", "product"])
print(indexed.groupby(level="region")["units"].sum())
# region
# North 15
# South 18
# Name: units, dtype: int64
print(indexed.groupby(level=["region", "product"])["units"].sum().head(2))
# region product
# North A 10
# B 5
# Name: units, dtype: int64level accepts a level name, a level number (level=0), or a list of either. The number counts from the outermost level. Names are safer, because adding a level later does not silently change which one you group by.
You can also write indexed.groupby("region"). Modern pandas accepts index level names in by as well as column names. This is convenient, but it can be ambiguous.
Grouping by a computed Series or array
The key does not have to exist in the DataFrame. Any Series or array with one value per row works. This lets you group by a condition, a derived value, or a transformed column without adding a helper column to the data.
big_sale = (df["revenue"] > 80).rename("big_sale")
print(df.groupby(big_sale)["units"].sum())
# big_sale
# False 15
# True 18
# Name: units, dtype: int64The result index takes its name from the Series, which is why rename is useful. Without it, the index would carry the name revenue, which would mislead anyone reading the output.
Computed keys can be mixed with column names in one list:
mixed = df.groupby(["region", big_sale])["units"].sum()
print(mixed)
# region big_sale
# North False 5
# True 10
# South False 10
# True 8
# Name: units, dtype: int64A Series key aligns on the index, not on position
When the key is a Series, pandas matches it to the DataFrame by index label. Position is ignored. This is correct when both come from the same data. It is a trap when the key was built separately and its index is in a different order.
key = pd.Series(["x", "x", "y", "y", "y"], index=[4, 3, 2, 1, 0])
print(df.groupby(key)["units"].sum())
# x 11
# y 22
# Name: units, dtype: int64Row 0 of df is matched to the key labeled 0, which is the last "y". If pandas had used position, row 0 would have been "x", and the sums would be 15 and 18. A plain list or NumPy array has no index, so it is matched by position. If you want position-based matching for a Series, pass key.to_numpy().
Labels that exist in the DataFrame but not in the key Series get a missing key, and those rows are dropped from the result. The chapter on missing keys covers this behavior and how to change it.
Grouping with a mapping
A dict or a Series passed as by translates index labels into group names. This works well for rolling many labels up into fewer categories.
units_by_region = df.set_index("region")["units"]
mapping = {"North": "Domestic", "South": "Export"}
print(units_by_region.groupby(mapping).sum())
# Domestic 15
# Export 18
# Name: units, dtype: int64The mapping is applied to the index labels of the object being grouped. Here that index is region. A label that is absent from the mapping gets a missing key and its rows are dropped.
You can also pass a function. It is called once per index label, and its return value becomes the group name. Mappings are usually clearer and easier to test.
Choosing between the forms
Use these rules when more than one form could work.
- If the key already exists as a column, group by the column name. It is the most readable form, and the key shows up named in the result.
- If the data is already indexed by the key, such as a time series or a dataset with a meaningful MultiIndex, use
level=. - If the key is a condition or derived value, build it as a named Series and pass it directly. Avoid adding a temporary column unless you need that column later.
- If you are recoding labels into broader categories, use a mapping or
Series.mapto build a key. - If the key comes from another table, check that its index matches the DataFrame index before grouping.
Common mistakes
- Grouping by a high-cardinality column. Keys such as an ID or a timestamp create one group per row, and the aggregation does nothing useful. Check
ngroupsfirst. - Forgetting that key order sets level order. The sums are identical, but selecting with
.locon the result depends on the nesting. - Passing a misaligned Series. Look for unexpected missing groups or sums that do not match a manual check.
- Assuming a key column stays in the result. It moves into the index. The next chapters show
as_index=Falseandreset_indexfor keeping it as a column.
Exercise
Using the df above, write one expression that gives total units for each region, split by whether revenue is above 80, and state the units for South where revenue is above 80.
Show answer
Use df.groupby(["region", (df["revenue"] > 80).rename("bigsale")])["units"].sum(). The result has a MultiIndex of region and bigsale, and South with big_sale True has 8 units (only the row with revenue 120.0).
Exercise
A Series key has the same values as the rows but its index is reversed relative to df. Does groupby match by position or by index label, and how can you force position-based matching?
Show answer
groupby matches a Series key by index label, so a reversed index assigns different keys to the rows than their positions suggest. To force position-based matching, pass key.to_numpy() (or a list), which has no index.