All problems

Count Orders per Customer

easyPythonGroupBy

Whetcode Supply, the desk-gear shop, wants to know who its repeat buyers are before it designs a loyalty scheme. The scheme is being piloted one city at a time, so the support lead asks for the same tally city by city: for every account registered in the city under test, how many separate orders that account has placed, one entry per account.

Nothing in the order table says "3". Every row is one order and nothing more, and the shop has never stored a running tally, because a stored tally is one somebody has to remember to keep correct.

There is a second catch, and it is the one that has embarrassed this report before. An account that has never ordered leaves no trace whatsoever in the order table — and the loyalty team specifically wants to see those accounts, because a customer sitting at zero is the one worth a nudge. Note also that a city is a fact about the account, not about the order: an order row says nothing about where the person who placed it lives.

customers_df — one row per registered account. id is the number an order refers back to.

id name city signup_date
1 Priya Nair Austin 2022-01-15
2 Tom Becker Berlin 2022-03-02
3 Sofia Rossi Milan 2022-05-19
4 Liam OConnor Dublin 2023-01-08
5 Wei Zhang Austin 2023-04-27
6 Ana Mendes Austin 2023-09-12

orders_df — one row per order placed this year. customer_id says who placed it; quantity is how many units of that one product the order was for.

id customer_id product_id quantity order_date
1 1 1 2 2023-02-01
2 1 4 1 2023-02-01
3 2 2 1 2023-02-10
4 3 3 3 2023-03-05
5 4 5 5 2023-03-11
6 1 3 1 2023-04-02
7 5 1 4 2023-05-20
8 2 5 2 2023-05-22
9 3 4 1 2023-06-01
10 5 2 1 2023-06-15

Input

Both DataFrames above are already built for you — the customer and order rows are not read from input. What does arrive is a single line naming the city under test, spelled exactly as the city column spells it.

Task: Print a dict whose keys are the id of every registered customer in that city (whole numbers, in id order) and whose values are the number of orders that customer placed. An account with no orders must still appear, with a value of 0 — not left out, and not a missing value. If the shop has no accounts in that city at all, print an empty dict.

Example: if customer 7 had placed four orders and customer 8 had placed none, their entries would read 7: 4 and 8: 0.

Sign in to solve this problem

Reading problems is free for everyone — solving them (Run, Submit, and tracking what you've solved) needs an account.

Sign in

Discussion

Sign in to join the discussion — reading is open to everyone.

Loading comments…