Skip to main content
Albero Academy

apply, map & where

Transform values with vectorised ops, np.where, map and apply.

Cleaning & Transforming9 min

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

the fast paths
import numpy as np
df["package_inr"] = df["package"] * 100000 # vectorised — fastest
df["tier"] = np.where(df["package"] >= 7, "high", "standard") # if/else

map & apply

lookups and custom logic
# 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

  1. 01Prefer vectorised expressions — they are the fastest and clearest.
  2. 02np.where(cond, a, b) is a vectorised if/else for a whole column.
  3. 03map replaces values via a dict/function on a Series.
  4. 04apply runs arbitrary Python per element — flexible but slow; use it last.

Finished this chapter?

Mark it complete to track your progress through Pandas.