Per-buyer order count and days from signup to first order
users(user_id, join_date, favorite_brand) and orders(order_id, order_date, item_id, buyer_id, seller_id). For each buyer return buyer_id, delta_days_first_purchase (days between their join_date and their earliest order), and cnt_orders (their total number of orders).
import pandas as pd
def market_analysis(users: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
# your code here
Write the implementation.
Aggregate orders per buyer, then bring in the join date. Group orders by buyer_id for the first order date (min(order_date)) and the order count (size), merge that with users on buyer_id == user_id, and compute delta_days = (first_order - join_date).dt.days.
- ✗Using the latest order instead of the first for the delta
- ✗Counting user rows instead of order rows
- ✗Reporting per-order deltas instead of one per buyer
- →Why aggregate orders before merging with users?
- →How would a buyer with no orders appear in the output?
Reduce orders to one row per buyer (first date and count), then merge in the join date and subtract.
import pandas as pd
def market_analysis(users: pd.DataFrame, orders: pd.DataFrame) -> pd.DataFrame:
agg = (orders.groupby('buyer_id')
.agg(first_order=('order_date', 'min'),
cnt_orders=('order_id', 'size'))
.reset_index())
m = agg.merge(users, left_on='buyer_id', right_on='user_id')
m['delta_days_first_purchase'] = (m['first_order'] - m['join_date']).dt.days
return m[['buyer_id', 'delta_days_first_purchase', 'cnt_orders']]
The first order date and the order count both come from one grouping of the orders table; merging with users on the buyer key brings in join_date so the day delta can be computed. Using the latest order or counting user rows would answer a different question.