BBampaa

Lessons › Python

Python lesson

groupby, part 1

Read it left to right: group by Store, pick the Revenue column, add up each group. Abuja made 195 and Lagos 264. It's a pivot table in one line.

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

Example

groupby splits the rows into groups, then you summarise each group:

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

Output:

Abuja 195
Lagos 264

Key points

groupby("Store")Split the rows into groups, one per store.
["Revenue"]Pick the column to summarise.
.sum()Add up each group.

Put together: df.groupby("Product")["Revenue"].sum() gives each product's total.

Practice

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

1. Build a line that totals revenue for each product.
df.groupby("Product")["Revenue"].sum()
2. Build a line that totals quantity for each store.
df.groupby("Store")["Qty"].sum()
3. Find the total quantity sold for each product.
df.groupby("Product")["Qty"].sum()
4. Find the total revenue for each store.
df.groupby("Store")["Revenue"].sum()
5. Find the total revenue for each day.
df.groupby("Day")["Revenue"].sum()

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