kmail.at
contact

elsewhere

EnglishEN
← learning

pandas · difficulty ◆◆

pandas groupby() — split a DataFrame by key and summarise each group

groupby decides which rows exist before it computes anything — get size/count/dropna/observed wrong and the report still looks clean, just wrong.

One NaN in the minutes column and size() says 2 while count() and mean() both insist there was only 1 — groupby is where pandas quietly decides which rows count.

fully AI-generatedThis text is fully AI-generated and was published without human editorial review.

2026-10-27 · 5 min read

$ df.groupby()
8
signature parameters

self, by, level, as_index, sort, group_keys, observed, dropna — inspect.signature on pandas 3.0.3

56
methods on the GroupBy object

public callables on DataFrameGroupBy in 3.0.3, from sum and size to rank, rolling and value_counts

22
Cython kernels in pandas._libs.groupby

group_sum, group_mean, group_rank, group_quantile … counted in 3.0.3

3.0.0
observed default flipped

docstring versionchanged + whatsnew: 'Changed the default value of observed'

What it does

groupby(by) splits a frame on one or more keys and hands you a GroupBy object — nothing is computed yet. Calling a reduction on it (sum, mean, size, count, nunique, agg) collapses each group to a single row. Calling a filter or a transform (filter, head, transform, apply) hands rows back with the original index intact. as_index=True keeps the keys in the index; as_index=False keeps them as columns, which is the SQL shape you want before a merge or a to_csv. Four switches decide which rows survive the split: sort, dropna, observed and group_keys — and all four have defaults that change what lands in your result.

Why it matters

The alternative is a dict of lists and a for loop, and I've written that loop enough times to know it ends in a bug. One groupby call replaces it: revenue per region per channel, mean ticket time per team, group sizes to find the accounts holding most of the rows. It's also the cheapest way to audit a column — g.size() against g.count() tells you instantly how much of a column is missing per group, which no describe() will spell out for you. Learn the four defaults once and every per-group report you write afterwards writes itself.

Example

$ orders = pd.DataFrame({
    "region": ["west", "west", "east", "east", "west", "north", "east", "north"],
    "channel": ["web", "store", "web", "web", "web", "store", "store", "web"],
    "amount": [1290.0, 480.5, 2210.0, 175.0, 640.0, 890.25, 1500.0, 310.0],
})
orders.groupby(["region", "channel"], as_index=False)["amount"].sum()
  region channel   amount
0   east   store  1500.00
1   east     web  2385.00
2  north   store   890.25
3  north     web   310.00
4   west   store   480.50
5   west     web  1930.00

Two keys, as_index=False: keys come back as columns with a fresh 0..5 index, so this frame drops straight into a to_csv or a merge. Drop as_index=False and you get the same numbers indexed by a (region, channel) MultiIndex instead.

$ tickets = pd.DataFrame({
    "team": ["payments", "payments", "payments", "search", "search", "auth", "auth"],
    "minutes": [42.0, 8.0, 61.0, 12.0, float("nan"), 33.0, 51.0],
})
print(tickets.groupby("team")["minutes"].size())
print(tickets.groupby("team")["minutes"].count())
print(tickets.groupby("team")["minutes"].mean())
team
auth        2
payments    3
search      2
Name: minutes, dtype: int64
team
auth        2
payments    3
search      1
Name: minutes, dtype: int64
team
auth        42.0
payments    37.0
search      12.0
Name: minutes, dtype: float64

The same three-line audit I run on every new dataset. search holds 2 rows but only 1 usable minute value: size() counts rows, count() counts non-null, and mean() silently averages the single survivor. On a dashboard, '2 tickets' and 'avg 12 minutes' describe different data.

$ trips = pd.DataFrame({
    "city": pd.Categorical(["Rotterdam", "Rotterdam", "Utrecht", "Gent"],
                           categories=["Rotterdam", "Utrecht", "Gent", "Breda"]),
    "fare": [12.5, 9.0, 15.25, 7.5],
})
trips.groupby("city")["fare"].sum()
trips.groupby("city", observed=False)["fare"].sum()
city
Rotterdam    21.50
Utrecht      15.25
Gent          7.50
Name: fare, dtype: float64
city
Rotterdam    21.50
Utrecht      15.25
Gent          7.50
Breda         0.00
Name: fare, dtype: float64

Breda is a declared category with zero rows. pandas 3.0 defaults observed=True, so it disappears from line one; observed=False puts it back as 0.00 — the sum of an empty group, not NaN, which is exactly how an empty region ends up in a report looking like it sold nothing rather than like it wasn't measured.

$ tickets = pd.DataFrame({
    "team": ["payments", "payments", "payments", "payments", "search", "search", "auth", "auth", "auth"],
    "minutes": [42.0, 8.0, 61.0, 19.5, 12.0, 25.0, 33.0, 51.0, 27.0],
})
tickets.groupby("team").filter(lambda g: len(g) >= 3)
       team  minutes
0  payments     42.0
1  payments      8.0
2  payments     61.0
3  payments     19.5
6      auth     33.0
7      auth     51.0
8      auth     27.0

filter is a group-level predicate that returns whole groups as original rows — not a summary. search (2 rows) is gone entirely, and the surviving rows keep their original index, so you can still join this back onto the unfiltered frame.

$ leads = pd.DataFrame({
    "region": ["west", "west", "east", None, "north", None],
    "amount": [900.0, 450.0, 1200.0, 300.0, 780.0, 150.0],
})
leads.groupby("region")["amount"].sum()
leads.groupby("region", dropna=False)["amount"].sum()
region
east     1200.0
north     780.0
west     1350.0
Name: amount, dtype: float64
region
east     1200.0
north     780.0
west     1350.0
NaN       450.0
Name: amount, dtype: float64

450.0 of pipeline has no region. dropna=True is the default, so the first result quietly accounts for 3330.0 of a 3780.0 total and looks perfectly fine doing it. If 'unattributed' is a real bucket in your business, dropna=False is not optional.

Common flags

df.groupby("team")
split on one column label; keys land in the index
df.groupby(["region", "channel"], as_index=False)
SQL-style output: keys stay as columns, result gets a RangeIndex
.size() vs .count()
rows per group vs non-null values per column — they differ the moment a NaN appears
sort=False
groups in order of first appearance instead of sorted keys; skips the ordering step
dropna=False
keeps NaN/None as its own group instead of dropping those rows
observed=False
categorical grouper: also emit categories with zero rows (as 0.00, not NaN)
.filter(lambda g: len(g) >= 3)
keep or drop whole groups; returns original rows, original index
.get_group("search")
pull one group back out as a plain DataFrame for inspection

History

Older than the changelog it lives in

There is no 'groupby was added in X' entry anywhere in pandas' release notes — and I checked. The oldest whatsnew file in the repository is v0.4.x (September–October 2011), and it already talks about a 'significant groupby performance enhancement' from removing integrity checks during slicing. groupby was there before pandas started keeping notes, which is why its defaults, not its introduction, are what people argue about fifteen years later.

Design note: the defaults moved, twice

group_keys started defaulting to True in 2.0.0 (2023), and observed flipped from False to True in 3.0.0 — the docstring's own versionchanged block records both. groupby is also split-apply-combine with the 'apply' half pre-baked: sum, size and mean go through compiled kernels, while apply hands groups to your Python function one at a time. Same object, two very different cost profiles.

Under the hood

Under the hood: factorize once, then hit a Cython kernel

The split happens when you call groupby(), not when you call the reduction: keys go through factorize, a hash table that maps 'west'/'east'/'north' to integer codes, which is also why grouping by a high-cardinality string column costs something up front. sort=True then orders the group labels and remaps the codes; sort=False skips that step and keeps first-appearance order. The codes and the values are what pandas._libs.groupby consumes — 22 compiled kernels (group_sum, group_mean, group_var, group_rank, group_quantile …), each writing one output slot per group in a single pass over the column. Anything without a kernel falls through to _python_agg_general and runs your callable group by group, which is the path that gets slow. observed exists because a categorical's codes include categories with no rows; True lets pandas drop those slots before aggregating instead of carrying them through as empties.

Fun facts

Pros & cons

pros

  • + One expression replaces the dict-plus-for-loop that every per-group report starts as
  • + The GroupBy object carries 56 methods, so the split is reusable across size, mean, rank, rolling and value_counts
  • + as_index=False gives you merge-ready output with zero reset_index() cleanup

cons

  • − Four defaults (sort, dropna, observed, group_keys) each change which rows exist, all silently
  • − Reductions collapse but filter and transform don't — mixing them in one chain produces shape surprises
  • − groupby().apply() with a Python function is the slow path; built-in reductions are orders of magnitude cheaper on big frames

Takeaways

  1. 1Pass as_index=False whenever the grouped result feeds a merge, a CSV or a chart — you get keys as columns, no reset_index().
  2. 2Audit a column with size() next to count(); the gap is the missing-value count per group, per row of the report.
  3. 3filter() keeps whole groups and hands back the original rows and index; agg/mean collapse. Choose by the shape you need downstream.
  4. 4dropna=False and observed=False are both 'keep the empties' switches — the first for NaN keys, the second for unused categories, and both are off by default.
  5. 5Reach for transform('mean') to add a per-group value as a column without a merge, and skip apply() unless you truly need per-group Python.

Related commands

archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →

← all learning