← Data analysis with Python

groupby: summaries per group

Split the table into groups, summarize each, and combine the answers.

Start this lesson

Many questions are "per group": units per store, average score per class, rain per season. groupby does this in three steps people call split-apply-combine. It splits rows into groups by a column, applies a summary (sum, mean, max...) to each group, and combines the answers into one Series labeled by group. You write it as df.groupby("store")["units"].sum(): group by store, look at units, add them up.

import io
import pandas as pd

csv_text = """day,store,item,units,price
Mon,North,Coffee,30,3.5
Mon,North,Muffin,12,2.75
Mon,South,Coffee,22,3.5
Mon,South,Tea,9,3.0
Tue,North,Coffee,35,3.5
Tue,North,Tea,7,3.0
Tue,South,Coffee,18,3.5
Tue,South,Muffin,15,2.75
Wed,North,Muffin,10,2.75
Wed,South,Coffee,27,3.5
"""
sales = pd.read_csv(io.StringIO(csv_text))
by_store = sales.groupby("store")["units"].sum()
print(by_store)
print(sales.groupby("item")["units"].mean())

North sold 94 units and South 91. The second line gives the average units per row for each item. The result is a Series whose index is the group names, so by_store["North"] reads one value.

Choose the column (["units"]) before the summary. Otherwise pandas tries to sum every column, including text ones.

Add .sort_values(ascending=False) at the end to rank the groups.