Deriving new values ranges from fast vectorised expressions to arbitrary Python per row. Reach for the fastest tool that fits: vectorised first, then np.where / map, and apply only when nothing else works.
Vectorised & np.where
import numpy as npdf["package_inr"] = df["package"] * 100000 # vectorised — fastestdf["tier"] = np.where(df["package"] >= 7, "high", "standard") # if/else
map & apply
# map — replace values via a dict (on a Series)df["prog_full"] = df["programme"].map({"Data": "Data Analytics", "Web": "Web Dev"})# apply — arbitrary Python per element (slower; last resort)df["label"] = df["package"].apply(lambda p: "distinction" if p >= 7.5 else "pass")
Key takeaways
- 01Prefer vectorised expressions — they are the fastest and clearest.
- 02np.where(cond, a, b) is a vectorised if/else for a whole column.
- 03map replaces values via a dict/function on a Series.
- 04apply runs arbitrary Python per element — flexible but slow; use it last.
