New and returning customers per month
A pandas exercise from Pandasdrill. Solve it with a Python editor in your browser running real pandas, and it is checked the moment you submit.
The task
The growth team wants a monthly table of active customers, split into new and returning. A customer is new in the month of their first order and returning in any later month they order in. Count each customer once per month, and count orders of any status. Return the columns `month` (text like `2024-01`), `new` and `returning`, in calendar order, with 0 where there are none.
What this exercise teaches
transform("min") writes each customer's first month on every one of their rows, so one comparison labels the row. A customer who orders twice in a month would be counted twice, so drop_duplicates on month and customer comes before the count. crosstab then spreads the two labels into columns and fills the gaps with 0.
A hint if you get stuck
Give every order its month and the customer's first month. Comparing the two tells you new or returning. Then make sure a customer counts once per month before you count.
Try it now, free, no account needed
Your first 8 exercises on Pandasdrill are free. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro unlocks every exercise, timed mode and the certificate.
Open this exerciseMore exercises in Interview cases
- Revenue by country
- Repeat customers
- Month over month revenue growth
- Best-selling product in each region
- Customers who never ordered
- Average order value by segment
- New customers per month
- Second order within 30 days
- A join that inflates the total
- Top three customers and their share
- Value lost to cancellations
- Average days between orders
- Messy export: clean, then total
- A conversion funnel