Sub topic 12
Using apply with groupby
This chapter assumes you can write Python functions and lambdas, build a pandas Series and DataFrame, and select columns. You should also know what groupby does: it splits rows into groups by a key. Earlier chapters covered map and apply on whole Series and DataFrames. Here the same idea applies to each group.
What apply does on grouped data
After groupby, apply calls your function once for each group. The function receives that group's data, and pandas combines the results using the group keys.
The type of object your function receives depends on what you select before calling apply:
df.groupby("team")["score"].apply(func)passes each group'sscorevalues as a Series.df.groupby("team").apply(func)passes each group as a DataFrame.
The first form is the simpler one. This example computes the spread (max minus min) of scores for each team.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
print(df.groupby("team")["score"].apply(lambda s: s.max() - s.min()))The function returns one number per group, so the result is a Series indexed by team. Team x gives 6 and team y gives 2.
Applying to whole groups
When you call apply on the grouped DataFrame, your function can use several columns. This example finds the best row in each team.
import pandas as pd
df = pd.DataFrame({
"team": ["x", "x", "y", "y"],
"player": ["ann", "bo", "cy", "di"],
"score": [3, 9, 4, 6],
})
def top_player(group):
return group.loc[group["score"].idxmax(), "player"]
print(df.groupby("team")[["player", "score"]].apply(top_player))Selecting [["player", "score"]] before apply is deliberate. Recent pandas versions warn when the function also receives the grouping column, and the behavior is changing. Selecting the columns you need avoids the warning and makes the intent clear.
Return shapes decide the result
The shape of the result follows what your function returns for each group.
| Function returns | Result |
|---|---|
| A scalar | A Series with one value per group |
| A Series | A DataFrame with one row per group |
| A DataFrame | Rows from all groups stacked, with the group key added to the index |
Returning a Series is a handy way to compute several statistics in one pass.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
def describe_scores(s):
return pd.Series({"low": s.min(), "high": s.max()})
print(df.groupby("team")["score"].apply(describe_scores))Prefer built-in group methods
Calling a Python function once per group is slower than using methods that pandas runs in compiled code. If a built-in does the job, use it.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
grouped = df.groupby("team")["score"]
print(grouped.max() - grouped.min())This gives the same answer as the lambda above. With many groups, the difference in speed can be large.
For named summaries, agg is often better than apply.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
print(df.groupby("team")["score"].agg(["min", "max"]))Use apply when the logic does not fit agg, transform or a built-in method. Typical cases are picking a row by a condition or returning a different number of rows for each group.
Common pitfalls
- Unstable result shape. If your function returns a scalar for some groups and a Series for others, the output is hard to predict. Return the same type every time.
- Grouping column in the data. When the function receives the whole DataFrame, the key column may be included. Select the columns you need first.
- Wrong tool for same-length output. To add a per-group value back onto every original row, such as a group mean, use
transform. It keeps the original index. - Empty groups and missing keys. Rows whose key is NaN are dropped by default. Pass
dropna=Falsetogroupbyif you need them.
Exercise
Given df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]}), write code that returns the mean score of each team using apply with a lambda. Then name a built-in method that gives the same result without apply.
Show answer
df.groupby("team")["score"].apply(lambda s: s.mean()) returns x 6.0 and y 5.0. The built-in df.groupby("team")["score"].mean() gives the same result and is faster, because pandas does not call a Python function for each group.
Exercise
You want a new column holding each row's score minus its team's mean score. Should you use apply or transform on the grouped Series, and why?
Show answer
Use transform. It returns a result with the same index as the original data, so you can assign it as a column: df["centered"] = df["score"] - df.groupby("team")["score"].transform("mean"). An apply that returns one scalar per group would produce one row per team and would not align with the original rows.