Python · medium

Explain the difference between .apply(), .map(), and vectorized ops in pandas.

Asked in Data Scientist interviews, in the Python round.

Short answer

Vectorized ops are fastest; map is element-wise on Series; apply is flexible but slower (row/col).

How to answer it

Three ways to transform a column, at three speeds.

df["cents"] = df["price"] * 100                          # vectorized
df["region"] = df["country"].map(COUNTRY_TO_REGION)      # dict lookup
df["label"] = df.apply(lambda r: f"{r.sku}-{r.size}", axis=1)   # slow; avoid at scale
df["label"] = df["sku"] + "-" + df["size"]               # the same, vectorized

The rule: reach for apply(axis=1) only when the logic genuinely needs several columns and cannot be expressed with np.where, np.select, or arithmetic. On a million rows the difference is seconds versus minutes.

Related questions

Practice this for real