skip to content

In pandas 3.0, why does a function passed to df.groupby('dept').apply() raise KeyError on g['dept'], and how do you fix it?

level: seniorimportance: should knowfreq 50%

answer

  1. the groupings are excluded
  2. include_groups no longer accepts True
  3. every group carries a name
  4. select columns explicitly

basics

~10 s

In pandas 3.0, DataFrameGroupBy.apply passes each group without the grouping columns, and include_groups=True raises ValueError. Read the key from g.name, or select the columns you need, key included, right after groupby.

solid answer

~30 s

Since pandas 3.0, `df.groupby('dept').apply(f)` hands `f` each department's rows **without** the `dept` column, so `g['dept']` raises `KeyError`. The `include_groups` argument that 2.2 added to opt out now defaults to `False`, and passing `include_groups=True` raises `ValueError: include_groups=True is no longer allowed.` The fix depends on what `f` needs: `g.name` holds the group's key (a tuple when you group by several keys); selecting columns explicitly, `df.groupby('dept')[['dept', 'amount']].apply(f)`, passes `dept` because you asked for it; and the key is already in the result's index when `f` returns a value per group. The same exclusion applies to a key given as `df['dept']` or `pd.Grouper(key='dept')`.

code

python · 15 lines
python
import pandas as pd

sales = pd.DataFrame({
    "dept": ["toys", "toys", "food", "food"],
    "store": ["S1", "S2", "S1", "S2"],
    "amount": [100, 50, 300, 150],
})
print(sales.groupby("dept").apply(lambda g: list(g.columns)))

def summary(g):
    best = g.loc[g["amount"].idxmax(), "store"]
    return pd.Series({"dept_label": g.name, "top_store": best})

print(sales.groupby("dept").apply(summary))
print(sales.groupby("dept")[["dept", "amount"]].apply(lambda g: list(g.columns)))

go deeper

for a junior

Recall that in pandas 3.0 the function given to groupby apply does not receive the grouping columns, and that g.name gives you the group's key.

for a middle

Explain which key forms trigger the exclusion, why include_groups=True now raises ValueError, and how an explicit column selection passes the key through.

for a senior

Show how you would find and fix every affected apply in a 2.x codebase, including functions whose sums or maxima silently changed when the key column vanished.

for a principal

Plan the 3.0 upgrade so apply changes are caught by tests on result shape and values, not by production KeyErrors, and steer the team toward narrower GroupBy methods.

## What changed in pandas 3.0 `DataFrameGroupBy.apply(func)` calls `func` once per group with a DataFrame and combines whatever comes back. Through the 2.x line that DataFrame **included the grouping columns** by default, so a function written as `lambda g: g['dept'].iloc[0]` worked. pandas 2.2 deprecated that behaviour and added `include_groups` so code could opt out; **pandas 3.0 enforced the deprecation**: - `include_groups` now defaults to `False`, and the groupings are excluded from what `func` receives. - Passing `include_groups=True` raises `ValueError: include_groups=True is no longer allowed.` - The same change applies to `Resampler.apply`. So code migrated from 2.x fails with `KeyError: 'dept'` the first time `func` touches the key column, or quietly produces different results if it computed over all columns, for example `g.sum()` no longer adds up the key. ```python def top_store(g): return g.loc[g["amount"].idxmax(), "store"] sales.groupby("dept").apply(top_store) # fine: uses store and amount sales.groupby("dept").apply(lambda g: g["dept"]) # KeyError: 'dept' ``` ## Which columns are excluded A column is excluded when pandas recognises it as one of the groupings drawn from the frame itself: | how the key is given | `dept` passed to `func`? | |---|---| | `df.groupby('dept')` | no | | `df.groupby(df['dept'])` (the frame's own column) | no | | `df.groupby(pd.Grouper(key='dept'))` | no | | `df.groupby(df['dept'].rename('d'))` (renamed, so not matched to a column) | yes | | `df.groupby('dept')[['dept', 'amount']]` (explicit selection) | yes | Grouping by an index level excludes nothing, because the level was never a column. ## Why the change makes sense The key of each group is already known: it is the group's `name`, and `apply` puts it in the result's index whenever the function returns a value per group. Passing the key column into the function as well duplicated that information and made whole-frame operations inside the function, such as `g.sum()` or `g.max()`, silently include the key in their output, adding up numeric codes or concatenating text keys. Excluding it makes `apply` consistent with `transform` and with aggregations, which by default leave the grouping columns out of what they compute. ## Getting the key back 1. **Use the group's name.** pandas sets `g.name` on every group before calling `func`. With one key it is the key value, such as `'food'`; with several keys it is a tuple such as `('food', 'S1')`, which the function can unpack with `dept, store = g.name`. This is the most direct replacement for the common 2.x idiom `g['dept'].iloc[0]`, and it works the same whether the key came from a column, an index level or an external array. 2. **Select the columns you need.** An explicit column list after `groupby` is passed through as written, so `df.groupby('dept')[['dept', 'amount']].apply(f)` gives `f` the `dept` column again. It is also good hygiene, because it states which columns `f` depends on. 3. **Let the index carry it.** When `f` returns a scalar or a Series per group, `apply` places the key in the result's index, so `f` rarely needs to repeat it. 4. **Prefer a narrower method.** If `f` is really an aggregation, a transform or a filter, the dedicated GroupBy method is faster and makes the shape of the result obvious. ## Where the key ends up in the result Whether the key appears in the **index** of what `apply` returns is a separate setting, `group_keys` on `groupby`, which defaults to `True`. When `func` returns a piece of each group, such as `g.nlargest(2, 'amount')`, the result gets the key as an outer index level. With `group_keys=False` that level is not added, and because the column is also excluded under pandas 3.0, the key then appears **nowhere** in the result. Keep `group_keys=True`, or select the key column explicitly, when downstream code needs it. ## Migrating 2.x code - Search for `.apply(` after `groupby` and read each function for references to the key columns. - Run the test suite under pandas 2.2 first: its deprecation warning fires at each `apply` that operated on the grouping columns. - Replace `g['key'].iloc[0]` with `g.name`. - Re-check numeric results of functions that reduced over all columns, such as `g.sum()` or `g.max()`: the key column is no longer among them. - Remove `include_groups=False` arguments added during the 2.2 migration only if you want; they are still accepted and now match the default. The speed cost of `apply` compared with built-in methods is a separate question, and the general picture of how several grouping keys end up in a result is covered in the library-neutral material on grouping.

  • What is g.name when you group by two columns?
    A tuple of the key values for that group, for example `('food', 'S1')` for `df.groupby(['dept', 'store'])`. Unpack it inside the function, `dept, store = g.name`, rather than reading the two columns, which pandas 3.0 excludes from what the function receives.
  • Why did g.sum() inside apply change its output after the upgrade?
    In 2.x the sub-frame still held the grouping columns, so a sum over all columns added them up or concatenated them. In pandas 3.0 they are excluded, so `g.sum()` covers only the other columns and the result has fewer entries per group.
  • With group_keys=False, where does the department go after apply(lambda g: g.nlargest(2, 'amount'))?
    Nowhere. `group_keys=False` stops `apply` adding the key as an index level, and pandas 3.0 already removed the column from each group, so the result holds only the other columns. Keep the default `group_keys=True` or select `dept` explicitly when you need it.

  • Passing include_groups=True in pandas 3.0 brings the grouping columns back
  • apply still passes the grouping column; the KeyError must be a typo
  • Grouping by df['dept'] instead of 'dept' avoids the exclusion
  • g.name holds the column name 'dept' rather than the group's key
  • group_keys=False puts the key back into each group's frame

Assumes pandas 3.0: 2.x passed the grouping columns into apply (2.2 deprecated it with include_groups); 3.0 always excludes them.