Evaluating a Dispatch Change: Welch Test on Pickup Wait Times
Statistics & ExperimentsModel answerLast updated
Compute a Welch's t-test p-value on pickup wait times for one city and month, then judge whether the result is trustworthy and propose a sounder experiment for a shared fleet.
A ride-hailing company tested a new dispatch (routing) algorithm meant to shorten pickup wait, the time between a rider's request and the vehicle arriving. The test ran in one city (San Francisco) during July 2024, and users were assigned to a control or treatment variant.
You have two pandas DataFrames:
df_users:user_id,variantdf_rides:ride_id,ride_date,city,time_to_pickup
Assume df_rides also contains user_id (needed for the join) and that San Francisco appears under a single label such as "SF". Verify both before relying on them.
Clarify first. State your assumptions on: the variant labels and whether each user has exactly one variant; one-sided vs two-sided testing; the significance level; how to treat rides with a missing time_to_pickup; and whether ride_date is a date or a timestamp and in which time zone "July" is defined.
Part 1: compute the p-value. Write a Python function that:
- keeps only San Francisco rides from the whole of July 2024,
- attaches each ride's rider variant,
- runs Welch's t-test on
time_to_pickupbetween the two variants, - returns the p-value.
Cover the pitfalls: date parsing with an exclusive upper boundary, a join that neither duplicates nor drops rides silently, users who appear in more than one variant, missing values, and what the test statistic and degrees of freedom are.
Part 2: validity. Interpret the result. Is it significant at your chosen level? Can the team conclude the new algorithm reduces pickup wait? If not, design a better experiment, including metrics, duration, power and the analysis plan.
Hints
Hint 1
Use a half-open date range (on or after 1 July, strictly before 1 August) so that timestamps on 31 July are not lost, and check the join with a validation option and a count of rides lost.
Hint 2
Welch's test does not pool variances: the statistic is the difference in means divided by sqrt(s1^2/n1 + s2^2/n2), and the degrees of freedom come from the Welch-Satterthwaite formula. In SciPy this is ttest_ind with equal_var=False.
Hint 3
Ask who shares the supply: if both variants draw on the same drivers, one arm's behavior changes the other arm's wait times, so the arms are not independent. Think about randomizing time blocks or regions instead of riders.
Hint 4
Also notice that the randomization unit is the user but the analysis unit is the ride, so repeated rides by the same user are correlated and the naive standard error is too small.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Code and reasoning
Assumptions (stated up front). Two variants, control and treatment; each user has exactly one. Two-sided test at alpha = 0.05 (a one-sided test is defensible only if committed to before the experiment). Rides with a missing wait time are dropped from the test and counted. "July" is defined in the city's local time zone.
import pandas as pd
from scipy import stats
def welch_pvalue(df_users, df_rides, city="SF"):
# Each user must have exactly one variant
per_user = df_users.groupby("user_id")["variant"].nunique()
if (per_user > 1).any():
raise ValueError("Some users are in more than one variant")
users = df_users.drop_duplicates("user_id")
rides = df_rides.copy()
rides["ride_date"] = pd.to_datetime(rides["ride_date"])
in_window = (rides["ride_date"] >= "2024-07-01") & (rides["ride_date"] < "2024-08-01")
rides = rides[(rides["city"] == city) & in_window]
merged = rides.merge(users, on="user_id", how="inner", validate="m:1")
# Report: len(rides) - len(merged) rides had no variant
merged = merged.dropna(subset=["time_to_pickup"])
a = merged.loc[merged["variant"] == "control", "time_to_pickup"]
b = merged.loc[merged["variant"] == "treatment", "time_to_pickup"]
t, p = stats.ttest_ind(b, a, equal_var=False)
return p
Key points:
- Date filter: a half-open interval avoids dropping rides at timestamps after midnight on 31 July, which
<= "2024-07-31"would do. - Join:
validate="m:1"fails loudly if the user table has duplicate keys, which would otherwise multiply rides. An inner join drops rides without a known variant, so log how many. - Welch statistic: t = (mean_T - mean_C) / sqrt(s_T^2/n_T + s_C^2/n_C). Degrees of freedom follow Welch-Satterthwaite: (v1 + v2)^2 / (v1^2/(n1-1) + v2^2/(n2-1)), where v_i = s_i^2/n_i. It is the safer default because it stays valid when variances or group sizes differ.
- Wait times are right-skewed; with large n the t-test is fine for means, but check medians or a trimmed or log metric as a robustness view.
Complexity is O(n) for the filter, join and statistics.
Part 2: Is the conclusion valid?
Reading the result. A small p-value says the observed difference would be unlikely if the true means were equal, under the test's assumptions. It says nothing about effect size or causality. Report the direction, the absolute and relative difference (for example minutes and percent), and a confidence interval. With hundreds of thousands of rides, a trivial difference can be "significant". If p is above alpha, that is absence of evidence, not proof of no effect.
Threats to validity
- Unit mismatch. Randomization is by user, but the test treats each ride as independent. Heavy users contribute many correlated rides, so the standard error is too small and p is too optimistic. Fix: aggregate to one value per user and test on users, or use cluster-robust standard errors or a mixed model.
- Interference through the shared fleet. Both arms draw on the same drivers. If the new algorithm grabs the nearest cars for treatment riders, control riders wait longer, which inflates the apparent gap. Conversely, efficiency gains could spill over and shrink it. Either way the estimate is not the effect of rolling the algorithm out to everyone (a violation of SUTVA).
- Limited scope. One city and one month: no check on seasonality, events, supply conditions or other markets, so generalization is weak.
- Other issues. Check for a sample ratio mismatch between arms, selection effects (for example cancellations before pickup removing the longest waits, which is survivorship bias), and multiple looks at the data.
So the team cannot conclude the algorithm reduces pickup wait from this test alone, even with p < 0.05.
A better design
- Randomization unit: switchback (alternate the algorithm by city-region and time block, such as 30 to 60 minute windows, with random assignment and washout or buffer periods), or geo-randomization with matched regions, possibly with synthetic control. This keeps each market's fleet within one arm at a time.
- Duration: at least two to four full weeks so every day-of-week pattern appears several times in each arm; more if the unit count is small.
- Power: since the effective sample size is the number of time-region blocks, not rides, estimate variance from historical block-level wait times, set a minimum detectable effect (for example a 3% reduction), and compute the required number of blocks for 80% power.
- Metrics: primary is mean or median pickup wait per block; guardrails include ETA accuracy, cancellation rate, driver utilization and idle time, driver earnings, trip completion, and rider satisfaction or retention.
- Analysis: block-level difference in means with regression adjustment for hour, weekday and region; cluster-robust or randomization-inference standard errors; pre-registered hypothesis and stopping rule; segment checks (peak vs off-peak, airport zones).
Common mistakes
- Treating rides as independent when users were randomized.
- Using
<= 31 Julyon timestamps. - A many-to-many join that silently multiplies rows.
- Equal-variance t-test by default.
- Declaring causal success from p < 0.05 without addressing interference or looking at guardrails.