Average days between orders
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
Customer success wants to know how often each customer comes back. For every customer with at least two orders of any status, return the average number of days between one order and the next, with the columns `customer` and `avg_gap_days`.
What this exercise teaches
diff inside a groupby compares each order with the same customer's previous order, and each customer's first order gets a missing value. Averaging the gaps per customer leaves a missing value for customers with a single order, and dropna removes them. Three orders make two gaps, which is why the shortcut divides by count minus 1.
A hint if you get stuck
Sort each customer's orders by date and subtract the previous date from each one. A customer's first order has no previous date.
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
- Messy export: clean, then total
- New and returning customers per month
- A conversion funnel