Data analysis with pandas · Lesson 10 of 15
groupby: totals and averages by group
Split a table into groups and summarise each one: totals by shop, averages by class, several summaries at once with agg, and a bar chart.
"Total sales per shop", "average mark per class", "how many orders per day": all these questions have the same shape. Split the rows into groups, calculate something for each group, and put the answers together. In pandas that is groupby.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
print(df)shop item qty price total 0 North tea 5 2.5 12.5 1 South tea 3 2.5 7.5 2 North cake 2 3.5 7.0 3 East tea 4 2.5 10.0 4 South cake 6 3.5 21.0 5 North tea 1 2.5 2.5 6 East cake 2 3.5 7.0
The sales of three shops; total = qty × price.
One column, one summary
df.groupby("shop")["total"].sum() reads: group the rows by shop, take the total column, add it up per group. The result is a Series with the shop names as the index, sorted A to Z.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
print(df.groupby("shop")["total"].sum())
print(df.groupby("item")["qty"].mean())shop East 17.0 North 22.0 South 28.5 Name: total, dtype: float64 item cake 3.333333 tea 3.250000 Name: qty, dtype: float64
Other summaries work the same way: mean, min, max, count, median. size() counts the rows in each group. Sort the result to see the best group first.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
print(df.groupby("shop").size())
best = df.groupby("shop")["total"].sum().sort_values(ascending=False)
print(best)
print("Best shop:", best.index[0])shop East 2 North 3 South 2 dtype: int64 shop South 28.5 North 22.0 East 17.0 Name: total, dtype: float64 Best shop: South
Several summaries with agg
agg gives several results at once. Named aggregation lets you choose the names of the new columns: name=(column, function).
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
summary = df.groupby("shop").agg(
orders=("qty", "count"),
items=("qty", "sum"),
sales=("total", "sum"),
)
print(summary)orders items sales shop East 2 6 17.0 North 3 8 22.0 South 2 9 28.5
Grouping by two columns
Give a list of columns to group by every combination. as_index=False (or reset_index() afterwards) keeps the group names as normal columns, which is easier to read and to save. (If you ever group by a category column, also pass observed=True.)
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
by_two = df.groupby(["shop", "item"], as_index=False)["total"].sum()
print(by_two)shop item total 0 East cake 7.0 1 East tea 10.0 2 North cake 7.0 3 North tea 15.0 4 South cake 21.0 5 South tea 7.5
Chart the result
A grouped Series is ready for a chart: its index gives the bars' labels. plot(kind="bar") draws it with matplotlib, which you will meet properly in Charts with matplotlib and df.plot.
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
import matplotlib.pyplot as plt
per_shop = df.groupby("shop")["total"].sum()
print(per_shop.to_dict())
per_shop.plot(kind="bar", color="teal", title="Sales by shop (€)")
plt.xticks(rotation=0)
plt.tight_layout()
plt.show(){'East': 17.0, 'North': 22.0, 'South': 28.5}
✎ Exercise
Using the same sales table, print the number of items sold (qty) per item, and the average total per shop rounded to 2 decimals.
Hint: groupby("item")["qty"].sum(), then groupby("shop")["total"].mean().round(2).
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
# your code here
Expected output:
item cake 10 tea 13 Name: qty, dtype: int64 shop East 8.50 North 7.33 South 14.25 Name: total, dtype: float64
Show a solution
import pandas as pd
df = pd.DataFrame({
"shop": ["North", "South", "North", "East", "South", "North", "East"],
"item": ["tea", "tea", "cake", "tea", "cake", "tea", "cake"],
"qty": [5, 3, 2, 4, 6, 1, 2],
"price": [2.5, 2.5, 3.5, 2.5, 3.5, 2.5, 3.5],
})
df["total"] = df["qty"] * df["price"]
print(df.groupby("item")["qty"].sum())
print(df.groupby("shop")["total"].mean().round(2))item cake 10 tea 13 Name: qty, dtype: int64 shop East 8.50 North 7.33 South 14.25 Name: total, dtype: float64
Check yourself
1. What does df.groupby("city")["temp"].max() return?
It groups by city and takes the maximum temperature within each group.
2. What does size() give after groupby?
size() counts the rows per group.
3. In agg(sales=("total", "sum")), what is sales?
Named aggregation: the left side is the new column name; the tuple says which column and which summary.