BBampaa

Lessons › Python

Python lesson

Several totals at once

Lagos: 264 in total, 52.8 an order, 5 orders. Abuja: 195, 65 and 3. To split further, group by two columns in a list.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

.agg takes a list of summaries and gives a column for each:

df.groupby("Store")["Revenue"].agg(["sum", "mean", "count"])

Output:

sum mean count
Abuja 195 65 3
Lagos 264 52.8 5

Key points

.agg(["sum", "mean", "count"])A list of summaries, one column for each.
groupby(["Store", "Product"])Two columns in a list: a group for every store and product pair.
Same shapedf.groupby(group)[column], then .agg([...]) or one summary.

Put together: df.groupby("Store")["Revenue"].agg(["sum", "mean", "count"]).

Practice

Try each one in your head first, then open the answer.

1. Build a line that shows the total, average and count of revenue for each store.
df.groupby("Store")["Revenue"].agg(["sum", "mean", "count"])
2. Build a line that totals revenue for each store and product pair.
df.groupby(["Store", "Product"])["Revenue"].sum()
3. Find the total, average and count of revenue for each store.
df.groupby("Store")["Revenue"].agg(["sum", "mean", "count"])
4. Find the total quantity sold for each store and product pair.
df.groupby(["Store", "Product"])["Qty"].sum()
5. Your manager asks for each product's biggest and smallest order. Show the max and min revenue for each product.
df.groupby("Product")["Revenue"].agg(["max", "min"])

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed