Days since the previous order
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
For each order, return the number of days since the same customer's previous order as a Series of floats aligned with the original rows. A customer's first order is NaN. The orders are already in date order.
What this exercise teaches
groupby("cust")["date"].diff() subtracts the previous date within the same customer, leaving NaT for each customer's first order. Subtracting dates gives timedeltas, so .dt.days converts them to numbers. A plain diff would compare consecutive rows regardless of customer.
A hint if you get stuck
diff on a grouped column compares each row with the previous row of the same group. The result is a timedelta, and .dt.days reads the day count.
Try it now, free, no account needed
The first 15 tasks 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 adds timed mode and the certificate.
Open this exercise