CodeMIRAI
0 XP

groupby

2 min read 6 runnable examples Quiz included

groupby splits a table into groups, applies a calculation to each, and combines the results. It's the pandas version of SQL's GROUP BY and of a PivotTable.

splitapplycombinePune8875mean()Delhi9270mean()Pune81.5Delhi81.0df.groupby("city")["score"].mean()
groupby splits the rows by a column's values, applies a summary to each group, and combines the answers into one result.
Python
import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "East", "South", "East", "North"],
    "product": ["Laptop", "Phone", "Phone", "Laptop", "Laptop", "Phone", "Laptop"],
    "amount": [1200, 650, 700, 1150, 1300, 600, 1250],
})

print(sales.groupby("region")["amount"].sum())

Read it as: group by region, take the amount column, and sum it within each group.

Common aggregations

Python
import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "East", "South", "East", "North"],
    "amount": [1200, 650, 700, 1150, 1300, 600, 1250],
})
g = sales.groupby("region")["amount"]
print(g.mean().round(1))
print(g.count())
print(g.max())

Several aggregations at once

Python
import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "East", "South", "East", "North"],
    "amount": [1200, 650, 700, 1150, 1300, 600, 1250],
})
summary = sales.groupby("region")["amount"].agg(["count", "sum", "mean", "max"])
print(summary.sort_values("sum", ascending=False))

Grouping by two columns

Python
import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "East", "South", "East", "North"],
    "product": ["Laptop", "Phone", "Phone", "Laptop", "Laptop", "Phone", "Laptop"],
    "amount": [1200, 650, 700, 1150, 1300, 600, 1250],
})
print(sales.groupby(["region", "product"])["amount"].sum())

Pivot tables

A pivot table spreads one grouping across the columns, giving a grid like Excel's PivotTables:

Python
import pandas as pd

sales = pd.DataFrame({
    "region": ["North", "South", "North", "East", "South", "East", "North"],
    "product": ["Laptop", "Phone", "Phone", "Laptop", "Laptop", "Phone", "Laptop"],
    "amount": [1200, 650, 700, 1150, 1300, 600, 1250],
})
table = sales.pivot_table(index="region", columns="product", values="amount", aggfunc="sum", fill_value=0)
print(table)

A chart in one line

Python
import pandas as pd
import matplotlib.pyplot as plt

sales = pd.DataFrame({
    "region": ["North", "South", "North", "East", "South", "East", "North"],
    "amount": [1200, 650, 700, 1150, 1300, 600, 1250],
})
sales.groupby("region")["amount"].sum().plot(kind="bar", title="Sales by region", color="#5a48f5")
plt.tight_layout()
plt.show()
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.