Python
All Top Python Interview Questions#19
Vectorization vs apply() vs iterrows(): Performance Benchmarks in Pandas
MediumGoogleInterview Question #19
Asked at GoogleGiven a DataFrame with 1 million rows containing `quantity` and `unit_price`, compute `total_revenue = quantity * unit_price`. Compare the performance of `iterrows()`, `.apply(axis=1)`, and direct vectorization.
Input Table: df
1 rows preview| rows | quantity | unit_price |
|---|---|---|
| 1,000,000 rows | 5 | 20 |
Expected Output Structure3 rows
| method | runtime |
|---|---|
| df['q'] * df['p'] (Vectorized) | 3 ms (Fastest) |
| df.apply(axis=1) | 1,200 ms |
| for row in df.iterrows() | 28,000 ms (Slowest) |
Interview Context
Asked frequently in data analyst and business analyst technical rounds. Focus on clean filtering, optimal indexing usage, and unambiguous column selection.
Python 3.10 (Pandas)
Environment Ready
Starting the real Python + pandas runtime (one-time download)…