groupby() (Pandas)

df.groupby() splits a DataFrame into groups based on the values in one or more columns, so you can apply an aggregation (sum, mean, count) to each group independently. It is pandas' split-apply-combine engine.

Pandas

The mental model is split-apply-combine: groupby splits the rows by key, you apply a function to each group, and pandas combines the results back into a new Series or DataFrame indexed by the group keys. groupby('city')['sales'].sum() gives total sales per city in one line.

By itself groupby('key') is lazy — it returns a GroupBy object and does no work until you call an aggregation, .agg(), .transform(), .filter(), or .apply() on it. You can group by several columns at once to get a MultiIndex result, and as_index=False keeps the keys as ordinary columns.

It is the single most important tool for summarising data in pandas, the direct equivalent of SQL's GROUP BY clause.

Syntax

df.groupby(by, as_index=True, sort=True)

Examples

Python

import pandas as pd
df = pd.DataFrame({"k": ["a", "a", "b"], "v": [1, 2, 3]})
print(df.groupby("k")["v"].sum())

Output:

k
a    3
b    3
Name: v, dtype: int64

Learn it in a lesson

See also

Back to the Dictionary