BBampaa

Lessons › Python

Python lesson

groupby, part 3

Lagos sold 590 against a target of 600: 0.98, so 98% of target. Abuja sold 370 against 400: 0.93, further below.

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

Example

Total two columns by the same group, then divide one by the other:

sales = df.groupby("Store")["Sales"].sum()
target = df.groupby("Store")["Target"].sum()
round(sales / target, 2)

Output:

Abuja 0.93
Lagos 0.98

Key points

Two groupbysTotal each column by the same group: sales per store, target per store.
sales / targetDivide them. Each store lines up with its own target: Lagos 590 / 600.
round(..., 2)Tidy the result: 0.9833 becomes 0.98, which is 98% of target.

Put together: round(sales / target, 2) gives each store's share of its target. Many shops aim for 1.0 or above: on target.

Practice

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

1. Build a line that totals the target for each store, into target.
target = df.groupby("Store")["Target"].sum()
2. Build a line that shows each store's sales as a share of its target, rounded to 2 decimal places.
round(sales / target, 2)
3. Work out each store's sales as a share of its target, rounded to 2 decimal places.
sales = df.groupby("Store")["Sales"].sum()
target = df.groupby("Store")["Target"].sum()
round(sales / target, 2)
4. Work out each week's sales as a share of its target, rounded to 2 decimal places.
sales = df.groupby("Week")["Sales"].sum()
target = df.groupby("Week")["Target"].sum()
round(sales / target, 2)
5. Show each store's share of all sales, rounded to 2 decimal places.
round(df.groupby("Store")["Sales"].sum() / df["Sales"].sum(), 2)

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