Python & Data Science

Pandas Groupby Reference Every Pattern You Ll Actu

You have a sales dataset. You need total revenue per region. You write a loop.

import pandas as pd
import numpy as np

# Our running example: an e-commerce sales DataFrame
np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})
df.head()

It works for the first region, but then you copy-paste the code three more times. It’s slow. It’s ugly. A colleague glances at your screen and says, “Just use groupby.” You try it:

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# The loop anti-pattern — what you probably wrote first
revenue_by_region = {}
for region in df['region'].unique():
    mask = df['region'] == region
    revenue_by_region[region] = df.loc[mask, 'revenue'].sum()
print("Loop result:", revenue_by_region)

# The groupby one-liner — what your colleague meant
print("\ngroupby result:")
print(df.groupby('region')['revenue'].sum())

Magic. One line, clean output, and it’s fast. You feel like a pandas wizard. Then your boss asks for revenue and profit per region, with mean, min, and max for each. You write:

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# The moment groupby stops being easy
result = df.groupby('region').agg({'revenue': ['sum', 'mean'], 'profit': ['sum', 'mean']})
print(result)
print("\nColumns:", result.columns)

And suddenly the output has these weird nested column labels. You can’t just do result['revenue'] the way you expected. The simplicity evaporated.

Here’s the core tension of groupby: it’s easy until it isn’t. One aggregation? Trivial. Two aggregations across two columns? Now you’re staring at a MultiIndex column structure and wondering where you went wrong.

This article is the map through that explosion. By the end, you’ll have a mental model for every groupby pattern you’ll actually encounter — and you’ll know exactly how to get flat, readable output every time.

Split-Apply-Combine: The Mental Model That Makes Everything Click

Before we dive into syntax, let’s build the intuition. Forget pandas for a moment. Imagine you’re holding a deck of playing cards.

You want to know how many cards of each suit you have. What do you do? First, you split the deck into four piles — one for hearts, one for diamonds, one for clubs, one for spades. Then, for each pile, you apply an operation: count the cards. Finally, you combine those counts into a little summary table: hearts 13, diamonds 13, clubs 13, spades 13.

That’s it. That’s the entire conceptual backbone of groupby. The pandas library is literally designed around this three-step process:

  1. Split: Divide the rows of your DataFrame into groups based on some key (like a column value).
  2. Apply: Do something to each group independently — sum it, average it, filter it, transform it.
  3. Combine: Stack the results from each group back together into a new DataFrame or Series.

In pandas, df.groupby('key') is the split step. It doesn’t actually do anything yet — it just creates a GroupBy object, a kind of blueprint that knows how the groups are defined. Nothing happens until you call an apply method.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# The split step alone does nothing visible
grouped = df.groupby('region')
print(type(grouped))
print(grouped)  # Just a GroupBy object, not a DataFrame

The apply step is where the real work happens, and it comes in three families — and this is the hardest part to keep straight when you’re learning. The pandas docs define them explicitly:

  • Aggregation: Collapses each group into a single row. Think .sum(), .mean(), .count(). One row per group.
  • Transformation: Returns an object with the same shape as the input. Every row gets a value, but that value is computed using its group’s context. Think .transform('mean').
  • Filtration: Decides which entire groups to keep or discard based on a condition. Think .filter(lambda g: g['revenue'].sum() > 1000).

This taxonomy isn’t just a teaching metaphor — it’s how the library is designed. Every subsequent section in this article is just a different flavor of “apply.” Once you can look at a problem and say “I need aggregation here” or “this calls for a transformation,” you’ve won.

Splitting: Every Way to Define Your Groups

Now that the mental model is in place, let’s explore all the practical ways to split a DataFrame. The most common case — a single column — covers about 90% of real-world usage. But the other 10% includes some genuinely useful patterns.

Single-column grouping

This is the one you already know. Pass a column name, and pandas groups rows that share the same value in that column.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Single-column grouping — the 90% case
grouped = df.groupby('region')
print("Group sizes:")
print(grouped.size())
print("\nGroups created:")
print(grouped.groups.keys())

Multi-column grouping

Pass a list of column names, and pandas creates hierarchical groups — one for every unique combination of values. Think of it as “group by region, and then within each region, group by product.”

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Multi-column grouping — hierarchical groups
grouped = df.groupby(['region', 'product'])
print("Group sizes (first 6):")
print(grouped.size().head(6))
print("\nGet a specific group:")
print(grouped.get_group(('North', 'Widget')).head(3))

Grouping by a function

Sometimes the group key isn’t a column — it’s something you compute from a column. Pass a function (or a Series) that produces the group labels, and pandas will use those labels to split the data.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Group by year — compute the group key on the fly
grouped = df.groupby(df['date'].dt.year)
print("Group sizes by year:")
print(grouped.size())

# You can also pass a function that takes the index
grouped_by_quarter = df.groupby(lambda idx: df.loc[idx, 'date'].quarter)
print("\nGroup sizes by quarter:")
print(grouped_by_quarter.size())

Grouping by a mapping or dict

When you want to merge existing categories into broader groups, a dictionary mapping is elegant. Pass a dict that maps existing values to new group labels.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Merge regions into broader categories
region_mapping = {'North': 'North Region', 'South': 'South Region',
                  'East': 'East Region', 'West': 'West Region'}
# For a more interesting merge, let's combine North+South and East+West
region_mapping = {'North': 'North-South', 'South': 'North-South',
                  'East': 'East-West', 'West': 'East-West'}
grouped = df.groupby(region_mapping)
print("Group sizes after mapping:")
print(grouped.size())

Key parameters that control split behavior

Now here’s the interesting part. The groupby() method has several keyword arguments that quietly change how your groups behave. Most people ignore them until they get burned.

as_index: Controls whether the group keys become the index of the result. as_index=True (the default) gives you the group keys as the index — clean for further pandas operations. as_index=False gives you SQL-style output with a default RangeIndex and the group keys as regular columns. But wait — this parameter only affects aggregation methods. It has no effect on filtration methods like head(), tail(), or nth(). This is one of the most common gotchas.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# as_index=True (default): group keys become the index
result_index = df.groupby('region', as_index=True)['revenue'].sum()
print("as_index=True (default):")
print(result_index)
print("\nIndex:", result_index.index)

# as_index=False: SQL-style output, group keys are columns
result_no_index = df.groupby('region', as_index=False)['revenue'].sum()
print("\nas_index=False:")
print(result_no_index)
print("\nIndex:", result_no_index.index)

sort: By default, sort=True, and pandas sorts the group keys alphabetically (or numerically). This is convenient for consistent output, but it adds computational overhead. If you have many groups and don’t care about the order, sort=False can give you a meaningful speedup. What this actually means: sort=False preserves the order in which group keys first appear in the data — not the row order within groups, just the order of the group labels themselves.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# sort=True (default): group keys are sorted
result_sorted = df.groupby('region', sort=True)['revenue'].sum()
print("sort=True (default):")
print(result_sorted)

# sort=False: group keys appear in order of first occurrence
result_unsorted = df.groupby('region', sort=False)['revenue'].sum()
print("\nsort=False:")
print(result_unsorted)

dropna: By default, dropna=True, and rows where the group key is NaN are silently excluded from the groups. If NaN is a meaningful category in your data — for example, missing region codes that you want to track — set dropna=False and NaN becomes its own group.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Introduce some NaN group keys
df_with_nan = df.copy()
df_with_nan.loc[df_with_nan.sample(10).index, 'region'] = np.nan

# dropna=True (default): NaN groups are silently dropped
result_dropna = df_with_nan.groupby('region', dropna=True)['revenue'].sum()
print("dropna=True (default) — NaN group excluded:")
print(result_dropna)

# dropna=False: NaN becomes its own group
result_keepna = df_with_nan.groupby('region', dropna=False)['revenue'].sum()
print("\ndropna=False — NaN group included:")
print(result_keepna)

Aggregation: From One Number to a Full Summary Table

Aggregation is the most common apply step: collapse each group into a single row. The built-in aggregation methods — sum, mean, std, min, max, count, nunique, first, last, median, var, sem, prod — are Cython-optimized. They’re fast. Use them whenever you can.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Built-in aggregations — fast, Cython-optimized
print("Sum:")
print(df.groupby('region')['revenue'].sum().head())
print("\nMean and std together:")
print(df.groupby('region')['revenue'].agg(['mean', 'std']).head())

But here’s the catch: the moment you ask for multiple aggregations, pandas gives you MultiIndex columns. Look at the output above — the columns are ('revenue', 'mean') and ('revenue', 'std'), not just 'mean' and 'std'. This is the exact frustration point from the introduction.

The .agg() method and the MultiIndex problem

.agg() (or its alias .aggregate()) is the swiss-army knife of aggregation. You can pass it a single function, a list of functions, or a dict mapping columns to functions. But the output shape changes depending on what you pass.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Single function — clean output
result_single = df.groupby('region')['revenue'].agg('sum')
print("Single function:")
print(result_single.head())
print("\nColumns:", result_single.columns if hasattr(result_single, 'columns') else 'N/A (Series)')

# List of functions — MultiIndex columns appear
result_list = df.groupby('region')['revenue'].agg(['sum', 'mean', 'std'])
print("\nList of functions:")
print(result_list.head())
print("\nColumns:", result_list.columns)

# Dict mapping columns to functions — MultiIndex gets worse
result_dict = df.groupby('region').agg({'revenue': ['sum', 'mean'], 'profit': ['min', 'max']})
print("\nDict of functions:")
print(result_dict.head())
print("\nColumns:", result_dict.columns)

The NamedAgg fix: flat, readable column names

The modern best practice — and the solution to the MultiIndex headache — is the NamedAgg pattern. Instead of passing strings or lists, you pass keyword arguments where the key is the desired output column name and the value is a tuple of (column, function).

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# NamedAgg — the modern best practice for clean output
result_named = df.groupby('region').agg(
    total_revenue=('revenue', 'sum'),
    avg_revenue=('revenue', 'mean'),
    min_profit=('profit', 'min'),
    max_profit=('profit', 'max')
)
print("NamedAgg — flat, readable column names:")
print(result_named)
print("\nColumns:", result_named.columns)

# Tuple shorthand — same thing, slightly less verbose
result_tuple = df.groupby('region').agg(
    total_revenue=('revenue', 'sum'),
    avg_revenue=('revenue', 'mean'),
    min_profit=('profit', 'min'),
    max_profit=('profit', 'max')
)
print("\nTuple shorthand (equivalent):")
print(result_tuple.head())

This is the pattern you should reach for first. It gives you exactly the column names you want, with no MultiIndex to fight.

Custom aggregation functions — and the performance cost

You can pass any function to .agg(), including lambdas. But here’s the hard truth: built-in aggregations run in Cython. Custom Python functions run in plain Python. The difference is often 10x or more.

import pandas as pd
import numpy as np
import time

np.random.seed(42)
n = 10000  # Larger DataFrame to make the difference visible
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Built-in sum — Cython-optimized
start = time.time()
result_builtin = df.groupby('region')['revenue'].sum()
builtin_time = time.time() - start
print(f"Built-in .sum(): {builtin_time:.4f} seconds")

# Custom lambda — plain Python
start = time.time()
result_lambda = df.groupby('region')['revenue'].agg(lambda x: x.sum())
lambda_time = time.time() - start
print(f"Lambda x.sum(): {lambda_time:.4f} seconds")
print(f"Slowdown: {lambda_time/builtin_time:.1f}x")

So what does that mean for us? Use built-in aggregations whenever they exist. Reach for custom functions only when you genuinely need logic that pandas doesn’t provide out of the box.

Manual MultiIndex flattening (the fallback)

If you find yourself with MultiIndex columns and NamedAgg doesn’t cover your case, you can flatten them manually. This is the Practical Business Python trick: join the tuple levels with an underscore.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Create a MultiIndex result the old way
result_multi = df.groupby('region').agg({'revenue': ['sum', 'mean'], 'profit': ['min', 'max']})
print("Before flattening:")
print(result_multi.columns)

# Manual flattening — the pbpython trick
result_multi.columns = ['_'.join(col).rstrip('_') for col in result_multi.columns.values]
print("\nAfter flattening:")
print(result_multi.columns)
print("\n")
print(result_multi.head())

Transformation: When You Need the Same Shape Back

Aggregation collapses groups. Transformation doesn’t — it returns an object with the same shape as the input. This is the hardest concept in groupby for most learners, so let’s spend real time here.

Think of it this way: you have sales data, and you want to know how each day’s revenue compares to the average revenue for that region. You can’t use aggregation — that would collapse everything to one row per region. You need .transform('mean'), which computes the per-group mean and then broadcasts it back to every row in that group.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Aggregation: one row per group
agg_result = df.groupby('region')['revenue'].mean()
print("Aggregation — one row per group:")
print(agg_result)
print(f"\nShape: {agg_result.shape}")

# Transformation: same shape as input
df['region_avg_revenue'] = df.groupby('region')['revenue'].transform('mean')
df['revenue_vs_avg'] = df['revenue'] - df['region_avg_revenue']
print("\nTransformation — new columns added to original DataFrame:")
print(df[['region', 'revenue', 'region_avg_revenue', 'revenue_vs_avg']].head(10))
print(f"\nShape: {df.shape}")

The core intuition: aggregation says “tell me about each group.” Transformation says “tell me about each row, using its group as context.” Every row now knows how its revenue compares to its region’s average.

Built-in transformation methods

Pandas provides several built-in methods that are shape-preserving and Cython-optimized. The most useful ones: cumsum (cumulative sum within each group), cumcount (cumulative count), diff (difference from previous row within group), shift (lag/lead within group), rank (ranking within group), ffill/bfill (forward/backward fill within group), and pct_change (percentage change from previous row within group).

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Sort by date within each region for meaningful cumulative/diff operations
df_sorted = df.sort_values(['region', 'date'])

# Cumulative sum within each region
df_sorted['cumsum_revenue'] = df_sorted.groupby('region')['revenue'].cumsum()

# Difference from previous day within each region
df_sorted['daily_change'] = df_sorted.groupby('region')['revenue'].diff()

# Rank within each region (1 = highest revenue)
df_sorted['revenue_rank'] = df_sorted.groupby('region')['revenue'].rank(ascending=False)

print("Transformations added to DataFrame:")
print(df_sorted[['region', 'date', 'revenue', 'cumsum_revenue', 'daily_change', 'revenue_rank']].head(10))

Custom transformation: group-wise z-score

You can pass custom functions to .transform(). The most common pattern is group-wise standardization — turning each value into a z-score within its group. The function receives each column of each group as a Series and must return a like-indexed Series or a scalar that can be broadcast.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Group-wise z-score standardization
df['revenue_zscore'] = df.groupby('region')['revenue'].transform(lambda x: (x - x.mean()) / x.std())

print("Original revenue and group-wise z-score:")
print(df[['region', 'revenue', 'revenue_zscore']].head(10))

# Verify: z-scores within each group should have mean ≈ 0 and std ≈ 1
print("\nVerification — mean and std of z-scores per region:")
print(df.groupby('region')['revenue_zscore'].agg(['mean', 'std']))

The hard part: transform with the wrong shape

Here’s the trap: your transform function must return either a like-indexed Series or a scalar. If it returns something else — a DataFrame, a list, a Series with a different index — it will fail. Let’s see what happens.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# This works — returns a scalar, which gets broadcast
try:
    df['works'] = df.groupby('region')['revenue'].transform(lambda x: x.mean())
    print("Scalar return — works fine:")
    print(df[['region', 'revenue', 'works']].head(5))
except Exception as e:
    print(f"Error: {e}")

# This fails — returns a list, which can't be broadcast
print("\nTrying to return a list (will fail):")
try:
    df['fails'] = df.groupby('region')['revenue'].transform(lambda x: [1, 2, 3])
except Exception as e:
    print(f"Error: {type(e).__name__}: {e}")

When to use transform vs. apply: transform is for shape-preserving operations on individual columns. If you need multiple columns at once within a group (like fitting a regression), use apply — which we’ll cover next.

Filtration: Keeping or Discarding Whole Groups

Filtration is the least-used but often most elegant apply family. Instead of computing per-row or per-group statistics, filtration decides which entire groups to keep or discard based on a group-wise condition.

The classic example: keep only regions with total revenue above a threshold.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Before filtration
print("Before filtration — all regions:")
print(df.groupby('region')['revenue'].sum())
print(f"\nNumber of rows: {len(df)}")

# Keep only regions with total revenue above 120,000
threshold = 120000
df_filtered = df.groupby('region').filter(lambda g: g['revenue'].sum() > threshold)

print(f"\nAfter filtration — only regions with revenue > {threshold}:")
print(df_filtered.groupby('region')['revenue'].sum())
print(f"\nNumber of rows: {len(df_filtered)}")

Built-in filtration conveniences: head, tail, nth

Pandas classifies head(), tail(), and nth() as filtration methods, but they behave differently from .filter(). Instead of evaluating a condition on each group, they simply return a subset of rows from every group. They’re not filtering groups — they’re filtering within groups.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Sort by date within each region for meaningful head/tail
df_sorted = df.sort_values(['region', 'date'])

# head(2): first 2 rows from every group
print("head(2) — first 2 rows per region:")
print(df_sorted.groupby('region').head(2))

# tail(1): last row from every group
print("\ntail(1) — last row per region:")
print(df_sorted.groupby('region').tail(1))

# nth(0): first row per group (0-indexed)
print("\nnth(0) — first row per region:")
print(df_sorted.groupby('region').nth(0))

Here’s the hard part to remember: .filter() returns all rows from groups that pass a condition. .head(), .tail(), and .nth() return a subset of rows from every group — they don’t drop any groups. And the as_index parameter? It has no effect on any filtration method. The docs say so explicitly, but it’s unintuitive enough to be a common gotcha.

Practical pattern: use .filter() to remove small groups before aggregation — your summary tables will be cleaner. Use .head() to sample the first few transactions per customer for exploratory analysis.

The .apply() Swiss Army Knife — and When Not to Use It

.apply() is the most flexible groupby method. It passes each entire group as a DataFrame to your function, then combines whatever your function returns. It can do aggregation, transformation, or filtration depending on what you return.

But that flexibility comes at a cost: it’s slower than built-in methods, and its behavior can be surprising.

When .apply() is the right tool

.apply() shines when you need multiple columns simultaneously within each group. The classic example: fitting a simple linear trend per region and extracting the slope.

import pandas as pd
import numpy as np
from scipy import stats

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Sort by date within each region
df_sorted = df.sort_values(['region', 'date'])

# Fit a linear trend per region and extract the slope
def fit_trend(group):
    """Fit a linear regression of revenue on day number, return the slope."""
    x = np.arange(len(group))  # day number within group
    y = group['revenue'].values
    slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
    return pd.Series({'slope': slope, 'r_squared': r_value**2})

trend_results = df_sorted.groupby('region').apply(fit_trend)
print("Linear trend per region (slope = daily revenue change):")
print(trend_results)

This is something transform can’t do — transform passes each column separately, not the full group DataFrame. If you need the whole group at once, apply is your method.

When .apply() is the wrong tool

Anytime a built-in aggregation, transform, or filter method exists, use it instead of apply. The official pandas docs are explicit: “An operation split into multiple steps using built-in GroupBy operations will be more efficient than using apply with a user-defined Python function.”

import pandas as pd
import numpy as np
import time

np.random.seed(42)
n = 10000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# Built-in sum
start = time.time()
result_builtin = df.groupby('region')['revenue'].sum()
builtin_time = time.time() - start

# apply with sum
start = time.time()
result_apply = df.groupby('region')['revenue'].apply(sum)
apply_time = time.time() - start

print(f"Built-in .sum(): {builtin_time:.4f} seconds")
print(f".apply(sum):    {apply_time:.4f} seconds")
print(f"Slowdown: {apply_time/builtin_time:.1f}x")

Practical rule of thumb: try agg/transform/filter first. Only reach for apply if you genuinely need the full group DataFrame or a custom output shape.

The group_keys parameter

When you use .apply(), pandas adds the group keys to the index of the result by default. Sometimes that’s helpful — you can see which group each row came from. Sometimes it’s clutter. The group_keys parameter controls this.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# group_keys=True (default): group labels added to index
result_keys = df.groupby('region', group_keys=True)[['revenue', 'profit']].apply(lambda g: g.head(2))
print("group_keys=True (default) — group labels in index:")
print(result_keys)

# group_keys=False: cleaner output
result_nokeys = df.groupby('region', group_keys=False)[['revenue', 'profit']].apply(lambda g: g.head(2))
print("\ngroup_keys=False — no group labels:")
print(result_nokeys)

Groupby Gotchas: The Traps That Catch Everyone

This is the “I wish I’d known this six months ago” section. Each gotcha gets a short example and the fix.

Gotcha 1: GroupBy object does nothing visible

df.groupby('region') returns a GroupBy object, not a DataFrame. Nothing happens until you call an apply method. Forgetting this leads to “why is nothing happening?”

import pandas as pd
import numpy as np

np.random.seed(42)
n = 100
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South'], n),
    'revenue': np.random.uniform(10, 500, n).round(2)
})

# This does nothing visible
grouped = df.groupby('region')
print("Type:", type(grouped))
print("It's a GroupBy object, not a DataFrame. Call .sum() or .mean() to see results.")

Gotcha 2: Multi-agg produces MultiIndex columns

Fix with NamedAgg/tuple shorthand or manual flattening. (We covered this in the Aggregation section — NamedAgg is the modern best practice.)

Gotcha 3: as_index=False doesn’t affect filtration

head(), tail(), and nth() ignore as_index. They’re filtration methods, not aggregation.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 100
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South'], n),
    'revenue': np.random.uniform(10, 500, n).round(2)
})

# as_index=False works for aggregation
print("Aggregation with as_index=False:")
print(df.groupby('region', as_index=False)['revenue'].sum())

# as_index=False has NO effect on head()
print("\nhead() with as_index=False — index still has group keys:")
print(df.groupby('region', as_index=False).head(2))

Gotcha 4: sort=False preserves group key order, not row order

sort=False controls the order group keys appear in the output, not the order of rows within each group.

Gotcha 5: NaN group keys are dropped by default

Use dropna=False if NaN is a meaningful group in your data.

Gotcha 6: axis= is not a valid parameter

Old tutorials may show df.groupby('column', axis=1), but axis was removed from DataFrame.groupby() in modern pandas. If you need to group by columns, transpose first or use a different approach.

Gotcha 7: .apply() with custom functions is slow

Built-in methods are Cython-optimized. Custom Python functions run in plain Python. The difference can be 10-100x on large DataFrames.

Gotcha 8: .transform() with wrong-shaped returns

Your transform function must return a like-indexed Series or a broadcastable scalar. A list, a DataFrame, or a Series with a different index will raise an error.

Groupby vs. Pivot Table: When to Use Which

Many readers reach for pivot_table when they mean groupby, or vice versa. Here’s the relationship in one sentence: pivot_table is groupby plus reshape — it’s a convenience for creating cross-tabulated summaries.

If you need a long-format summary (one row per group), use groupby. If you need a wide-format summary (groups as both rows and columns), use pivot_table.

import pandas as pd
import numpy as np

np.random.seed(42)
n = 1000
df = pd.DataFrame({
    'region': np.random.choice(['North', 'South', 'East', 'West'], n),
    'product': np.random.choice(['Widget', 'Gadget', 'Doohickey'], n),
    'revenue': np.random.uniform(10, 500, n).round(2),
    'profit': np.random.uniform(1, 100, n).round(2),
    'date': pd.date_range('2024-01-01', periods=n, freq='D')
})

# groupby: long-format output (one row per group combination)
groupby_result = df.groupby(['region', 'product'])['revenue'].sum().reset_index()
print("groupby — long format:")
print(groupby_result.head(8))

# pivot_table: wide-format output (cross-tabulation)
pivot_result = df.pivot_table(values='revenue', index='region', columns='product', aggfunc='sum')
print("\npivot_table — wide format:")
print(pivot_result)

pivot_table uses groupby under the hood — it’s not a different aggregation engine, just a different output shape. Use groupby when you need to do further processing, merge with other DataFrames, or feed into plotting functions that expect long-format data. Use pivot_table for presentation, Excel-style summaries, or when you need groups as both rows and columns.

One more thing: pivot_table’s aggfunc defaults to 'mean'. groupby has no default aggregation — you must specify one.

Recap: The Groupby Patterns You’ll Actually Use

Here’s the decision heuristic to keep in your back pocket:

  • One row per group → Aggregation (.sum(), .mean(), .agg())
  • Same shape as input → Transformation (.transform(), .cumsum(), .shift())
  • Fewer groups → Filtration (.filter(), .head(), .tail())
  • Anything else → .apply() (but check performance first)

Most-used aggregation methods: sum, mean, count, nunique, min, max, std, first, last

Most-used transformation methods: cumsum, shift, rank, pct_change, group-wise standardization

Most-used filtration methods: filter (by condition), head, tail, nth

The NamedAgg pattern is the modern best practice for multi-function, multi-column aggregation — use it to avoid MultiIndex column headaches.

Performance rule: built-in methods are Cython-optimized. Custom Python functions in apply/agg/transform are slow — profile if you’re working with large data.

Check Your Understanding

Remember: What are the three steps of the split-apply-combine model?

Understand: In plain English, what’s the difference between aggregation and transformation? When would you use each?

Apply: Given a DataFrame of customer orders with columns customer_id, order_date, and order_value, write the code to add a column showing each order’s value relative to that customer’s average order value.

Analyze: You run df.groupby('category').agg({'sales': ['sum', 'mean'], 'profit': 'max'}) and get MultiIndex columns. Why did this happen, and what are two ways to get flat column names instead?

Evaluate: A colleague writes df.groupby('region').apply(lambda g: g['revenue'].sum()) to get total revenue per region. Is this a good approach? Why or why not?

Create: Design a groupby pipeline that, for each product category, identifies the top 3 performing regions by total revenue, and returns a flat DataFrame with columns category, region, total_revenue, and rank.

Apply What You Learned

Using the e-commerce sales DataFrame from this article (or your own sales data with at least a region column, a product column, a revenue column, and a date column), create a single script that produces:
  1. A flat summary table showing, for each region: total revenue, average profit, number of unique products sold, and the standard deviation of revenue — all with clean, single-level column names.
  2. A new column added to the original DataFrame showing each transaction’s revenue as a z-score within its region.
  3. A filtered DataFrame that excludes any region with total revenue below the median total revenue across all regions.

Deliverable: A single Python script that runs end-to-end and prints the three results.

Self-check rubric:

  • The summary table has flat column names (no MultiIndex).
  • The z-score column has mean ≈ 0 and std ≈ 1 within each region.
  • The filtered DataFrame has fewer rows than the original and only contains regions with above-median total revenue.
  • Python Engineering Under review

    Feature Engineering Techniques Reference A Checkli

    np.random.seed(42) n_samples = 500

  • Python Engineering Under review

    Reinforcement Learning Algorithms Reference Which

    Before we name a single algorithm, we need to name the axes that separate them. Otherwise, you’re memorizing names without knowing why they differ—like learning the names of every screwdriver without knowing whether your screw is flathead or Phillips. Let’s fix that.

  • Python Engineering Under review

    Regex Reference For Data Cleaning The Patterns Wor

    data = { "phone": [ "(555) 123-4567", "555.123.4567", "5551234567", "Call after 6pm: 555-123-4567", "N/A", ] } df = pd.DataFrame(data)

  • Python Engineering Under review

    Numpy Array Cheat Sheet The Operations You Ll Actu

    You’ve probably done this before: you open the official NumPy docs, scroll for thirty seconds, see a wall of function signatures, and close the tab. You don’t need a 50-page reference manual.

Looking for something else?

Search every article by title, summary or topic.