The request

From Angela Rivera, Head of Customer Support
Your goal
Link each return to its order (returns → order_items on order_item_id → orders on order_id). Days to return = returned_on minus the calendar day of order_date (time of day dropped), in whole days. Set result to a DataFrame with columns reason, n_returns (number of returns), avg_days (mean days to return, rounded to 1) and share_30d (share of returns with returned_on on or before the order day + 30 days, between 0 and 1, rounded to 3), one row per reason, sorted by avg_days ascending, index reset.
- Use the
ordersDataFramenot done yet - Use the
order_itemsDataFramenot done yet - Show exactly
reasonn_returnsavg_daysshare_30dnot done yet
Your code
Loading the editor…
Reference solution
| order_id | customer_id | order_date | status | channel |
|---|---|---|---|---|
| 1001 | 125 | 2023-01-01 20:51:19 | completed | web |
| 1002 | 156 | 2023-01-02 07:58:46 | completed | web |
| 1003 | 22 | 2023-01-02 10:25:27 | completed | marketplace |
| 1004 | 48 | 2023-01-02 11:21:51 | completed | marketplace |
Mote checks your result
Press Run. Each row that matches the goal becomes a firefly in your lantern.
What Angela gets, and why
DataFrames
Loaded for you as pandas DataFrames, plus pd and np.
orders12,000 rows · 7 columns
order_idintegercustomer_idintegerorder_datetimestampstatusvarcharchannelvarcharshipping_feedecimalcoupon_codevarchar
| order_id | customer_id | order_date | status | channel | shipping_fee | coupon_code |
|---|---|---|---|---|---|---|
| 1001 | 125 | 2023-01-01 20:51:19 | completed | web | 0.00 | NaN |
| 1002 | 156 | 2023-01-02 07:58:46 | completed | web | 0.00 | NaN |
| 1003 | 22 | 2023-01-02 10:25:27 | completed | marketplace | 4.99 | WELCOME10 |
| 1004 | 48 | 2023-01-02 11:21:51 | completed | marketplace | 4.99 | WELCOME10 |
| 1005 | 82 | 2023-01-02 11:43:36 | completed | web | 0.00 | WELCOME10 |
order_items30,338 rows · 6 columns
order_item_idintegerorder_idintegerproduct_idintegerquantityintegerunit_pricedecimaldiscount_pctdecimal
| order_item_id | order_id | product_id | quantity | unit_price | discount_pct |
|---|---|---|---|---|---|
| 1 | 1001 | 121 | 9 | 31.99 | 0.00 |
| 2 | 1001 | 154 | 3 | 11.99 | 0.00 |
| 3 | 1002 | 154 | 4 | 11.99 | 0.00 |
| 4 | 1002 | 194 | 1 | 149.00 | 0.00 |
| 5 | 1002 | 193 | 2 | 19.99 | 0.00 |
returns1,673 rows · 5 columns
return_idintegerorder_item_idintegerreturned_ondatereasonvarcharrefund_amountdecimal
| return_id | order_item_id | returned_on | reason | refund_amount |
|---|---|---|---|---|
| 1 | 14 | 2023-01-10 | damaged | 83.69 |
| 2 | 42 | 2023-01-10 | wrong_item | 19.99 |
| 3 | 105 | 2023-01-14 | wrong_item | 10.99 |
| 4 | 24 | 2023-01-16 | changed_mind | 26.99 |
| 5 | 126 | 2023-01-16 | late | 20.99 |
customers2,018 rows · 9 columns
customer_idintegerfirst_namevarcharlast_namevarcharemailvarcharcityvarcharstatevarcharsignup_datedatesegmentvarcharreferral_sourcevarchar
| customer_id | first_name | last_name | city | state | signup_date | segment | referral_source | |
|---|---|---|---|---|---|---|---|---|
| 1 | Owen | Hudson | owen.hudson@icloud.com | San Francisco | CA | 2022-06-02 | consumer | search |
| 2 | Douglas | Mendoza | dmendoza69@gmail.com | Atlanta | GA | 2022-06-02 | consumer | NaN |
| 3 | Henry | Brooks | hbrooks@lakesidecafe.com | Los Angeles | CA | 2022-06-04 | business | NaN |
| 4 | Brian | Graham | bgraham@bluecedarhomes.com | Seattle | WA | 2022-06-06 | business | |
| 5 | Kyle | Jimenez | kjimenez27@yahoo.com | Indianapolis | IN | 2022-06-07 | consumer | NaN |
products120 rows · 8 columns
product_idintegernamevarcharcategoryvarcharsubcategoryvarcharunit_pricedecimalunit_costdecimallaunched_ondateis_activeboolean
| product_id | name | category | subcategory | unit_price | unit_cost | launched_on | is_active |
|---|---|---|---|---|---|---|---|
| 101 | Vale Velvet Loveseat | Furniture | Sofas | 1659.00 | NaN | 2023-09-11 | true |
| 102 | Alder Oak Coffee Table | Furniture | Tables | 919.00 | 503.50 | 2024-05-16 | true |
| 103 | Orchard Rattan Dining Chair | Furniture | Chairs | 789.00 | 429.87 | 2023-05-27 | true |
| 104 | Upland Oak Bookcase | Furniture | Storage | 429.00 | 214.70 | 2022-12-20 | true |
| 105 | Avery Leather Bed Frame | Furniture | Beds | 449.00 | 232.70 | 2021-08-31 | true |
employees60 rows · 8 columns
employee_idintegerfirst_namevarcharlast_namevarchardepartmentvarchartitlevarcharmanager_idintegerhire_datedatesalaryinteger
| employee_id | first_name | last_name | department | title | manager_id | hire_date | salary |
|---|---|---|---|---|---|---|---|
| 1 | Catherine | Hale | Executive | Chief Executive Officer | NaN | 2016-03-01 | 285000 |
| 2 | Robert | Kim | Executive | Chief Operating Officer | 1 | 2017-01-09 | 235000 |
| 3 | Megan | Collins | Sales | Head of Sales | 1 | 2018-04-16 | 172000 |
| 4 | Chloe | Gutierrez | Sales | Account Executive | 3 | 2020-01-21 | 72000 |
| 5 | Frank | Bell | Sales | Account Executive | 3 | 2023-05-21 | 73000 |
web_sessions40,000 rows · 7 columns
session_idintegercustomer_idintegerstarted_attimestampdevicevarcharsourcevarcharpages_viewedintegerconvertedboolean
| session_id | customer_id | started_at | device | source | pages_viewed | converted |
|---|---|---|---|---|---|---|
| 1 | NaN | 2023-01-01 23:02:24 | mobile | paid | 1 | false |
| 2 | 18 | 2023-01-01 15:07:49 | desktop | paid | 1 | false |
| 3 | NaN | 2023-01-01 16:55:46 | desktop | direct | 7 | false |
| 4 | NaN | 2023-01-01 12:43:28 | mobile | organic | 3 | false |
| 5 | NaN | 2023-01-01 13:06:21 | mobile | social | 2 | false |
marketing_spend3,276 rows · 3 columns
spend_datedatechannelvarcharamountdecimal
| spend_date | channel | amount |
|---|---|---|
| 2023-01-01 | paid | 492.99 |
| 2023-01-01 | 37.38 | |
| 2023-01-01 | social | 200.53 |
| 2023-01-02 | paid | 709.13 |
| 2023-01-02 | 64.13 |
The lesson
Subtracting dates
When you subtract one datetime column from another, pandas gives you a Timedelta column: a length of time, not a date.
r = (
returns.merge(order_items[["order_item_id", "order_id"]], on="order_item_id")
.merge(orders[["order_id", "order_date"]], on="order_id")
)
(r["returned_on"] - r["order_date"]).head(2)
# 0 7 days 12:16:24
# 1 5 days 12:47:48
The .dt accessor works on Timedeltas too: .dt.days gives the whole days, and
.dt.total_seconds() the exact length in seconds (divide by 86,400 for fractional days).
Watch the time of day
returned_on is a date (midnight), but order_date is a timestamp with a time. The first return
above belongs to an order placed at 11:43 on 2 January 2023 and came back on 10 January: “7 days
12:16” later. .dt.days drops the partial day and says 7, but on the calendar the return arrived 8
days after the order day. To count calendar days, set the order to midnight first with
.dt.normalize():
order_day = r["order_date"].dt.normalize()
r["days"] = (r["returned_on"] - order_day).dt.days
r["days"].mean() # 16.29 (15.29 without normalize)
A whole day of difference in the average from one missing method call: always check what kind of date each column holds.
Moving dates: Timedelta and DateOffset
To shift a date by a fixed length, add a pd.Timedelta:
order_day + pd.Timedelta(days=30) # 30 days later
orders["order_date"] - pd.Timedelta(hours=6)
For calendar-aware moves, use pd.DateOffset: pd.DateOffset(months=1) moves 31 January to
28 or 29 February, and pd.offsets.MonthEnd(0) rolls a date forward to the end of its month.
Timedelta is a fixed number of days; DateOffset follows the calendar. A “30-day window” is a
Timedelta; “until the end of next month” is a DateOffset.
The return window per reason
Once each row has days and a True/False within_30, a named aggregation answers Angela. The
mean of a boolean column is the share of True values:
# reason n_returns avg_days share_30d
# wrong_item 255 7.9 1.000
# damaged 477 8.0 1.000
# changed_mind 698 22.7 0.711
# late 243 22.9 0.741
Damaged and wrong items come back within about a week, all inside 30 days. Change-of-mind and late returns take three weeks on average, and roughly a quarter of them arrive after day 30. Overall, 84.2% of returns would fit the window, so the policy hits exactly the customers who changed their mind.
Common mistakes
- Subtracting a timestamp with a time of day and reading
.dt.daysas calendar days. - Calling
.dayson the column instead of.dt.days(it works on one Timedelta, not on a Series). - Adding a plain number to a date (
order_day + 30), which raises aTypeError. Wrap it inpd.Timedelta(days=30). - Using
pd.DateOffset(months=1)when the rule really is a fixed number of days, or the reverse.
Lantern lit!
Practised: timedeltadt daysdate offsetnormalizereturn window
- Solved
- No hints
- First run
