Percent of immediate orders among each customer's first order
delivery(delivery_id, customer_id, order_date, customer_pref_delivery_date). An order is immediate when the preferred date equals the order date, else scheduled. A customer's first order is the one with the earliest order_date (exactly one guaranteed per customer). Return the percentage of immediate orders among all customers' first orders, rounded to 2 decimals, as a one-cell DataFrame.
import pandas as pd
def immediate_pct(delivery: pd.DataFrame) -> pd.DataFrame:
# your code here
Write the implementation.
Pick each customer's first order, then take the share that are immediate. Get the first-order row indices with groupby('customer_id')['order_date'].idxmin(), select those rows, and compute the mean of the boolean order_date == customer_pref_delivery_date times 100, rounded to 2.
- ✗Computing the percentage over all orders, not first orders
- ✗Selecting the last order instead of the earliest
- ✗Dividing by customers without isolating first orders
- →Why use idxmin rather than sorting and taking head(1)?
- →How would ties on order_date affect the first-order pick?
Filter to each customer's first order, then take the mean of the immediate flag.
import pandas as pd
def immediate_pct(delivery: pd.DataFrame) -> pd.DataFrame:
first_idx = delivery.groupby('customer_id')['order_date'].idxmin()
firsts = delivery.loc[first_idx]
pct = round(
(firsts['order_date'] == firsts['customer_pref_delivery_date']).mean() * 100,
2)
return pd.DataFrame({'immediate_percentage': [pct]})
idxmin() returns the row index of the earliest order per customer; selecting only those rows gives one first order each. The boolean compare yields True for immediate orders, and .mean() * 100 is their percentage. Computing over all orders instead would answer a different question.