Pandasdrill

Level 7: Interview cases Exercise 99 of 102

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 exercise

More exercises in Interview cases