BBampaa

Lessons › Python

Python lesson

groupby, part 2

The average order is 65 in Abuja and 52.8 in Lagos. Lagos made more in total, but Abuja's orders are bigger on average.

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

Example

Swap .sum() for another method to summarise each group differently:

df.groupby("Store")["Revenue"].mean()

Output:

Abuja 65.0
Lagos 52.8

Key points

.mean()The average for each group.
.count()How many rows are in each group.
.max()The biggest value in each group.

Same shape every time: df.groupby(group)[column].method().

Practice

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

1. Build a line that finds the average revenue for each store.
df.groupby("Store")["Revenue"].mean()
2. Build a line that counts the orders for each day.
df.groupby("Day")["Order"].count()
3. Find the average revenue for each day.
df.groupby("Day")["Revenue"].mean()
4. Count the orders for each store.
df.groupby("Store")["Order"].count()
5. Find the biggest single order for each product.
df.groupby("Product")["Revenue"].max()

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