Last updated

Grouping Data

Definition: groupby splits the rows into groups that share a value, then lets you calculate a summary (sum, mean, count) for each group. It is one of the most powerful features in Pandas.

Example 1 — total per group

import pandas as pd
df = pd.DataFrame({
  "team":   ["A", "B", "A", "B", "A"],
  "points": [10, 20, 15, 25, 5]
})
print(df.groupby("team")["points"].sum())

This gives one total per team: A = 30, B = 45.

Example 2 — average per group

import pandas as pd
df = pd.DataFrame({"team": ["A","B","A","B"], "points": [10,20,15,25]})
print(df.groupby("team")["points"].mean())

Example 3 — count rows per group

import pandas as pd
df = pd.DataFrame({"city": ["London","Paris","London","Rome","London"]})
print(df.groupby("city").size())

💡 Think "split-apply-combine": split into groups, apply a calculation to each, combine the results into one table. This is the core of data reporting.

Try it Yourself
Output

          
Ad · responsive