apply(), map(), and Vectorisation
How you apply custom logic to a DataFrame column determines whether your script runs in 0.1 seconds or 60 seconds on a large dataset. This is a key interview differentiator.
What is the difference between apply(), map(), and applymap()?
# map() — on a Series, element-wise:
df["city"].map({"Delhi": "North", "Mumbai": "West"})
df["salary"].map(lambda x: x * 1.1) # 10% raise
# apply() — on a Series or DataFrame:
df["salary"].apply(lambda x: x * 1.1) # Series
df.apply(lambda col: col.max(), axis=0) # each column
# map() (DataFrame) / applymap() — element-wise on DataFrame:
df[["a","b"]].map(lambda x: round(x, 2))map() is for simple value-to-value transformations on a Series. apply() is more flexible — works on Series and DataFrames and supports complex functions. map() with a dict is the fastest way to do label encoding.
Why should you avoid using apply() with loops?
# Slow — apply() with loop-like logic:
df["result"] = df["salary"].apply(lambda x: x * 0.9 if x > 50000 else x)
# Fast — vectorised with np.where:
import numpy as np
df["result"] = np.where(df["salary"] > 50000, df["salary"] * 0.9, df["salary"])
# Even faster — direct arithmetic:
df["result"] = df["salary"] * 0.9 # if no conditionapply() calls a Python function row by row — it is essentially a loop. Vectorised NumPy operations process all values at once in C. On 1 million rows, np.where() is 10-100x faster than apply().
How do you use np.where() for conditional column logic?
# Single condition:
df["grade"] = np.where(df["score"] >= 60, "Pass", "Fail")
# Nested (like IF-ELSE):
df["band"] = np.where(df["salary"] > 90000, "Senior",
np.where(df["salary"] > 60000, "Mid", "Junior"))np.where(condition, value_if_true, value_if_false) is the vectorised equivalent of Excel IF(). Nesting np.where() replaces multiple if-elif branches. For more than 3 levels, use np.select().
How do you use np.select() for multiple conditions?
conditions = [
df["salary"] > 100000,
df["salary"] > 70000,
df["salary"] > 50000,
]
choices = ["Lead", "Senior", "Mid"]
df["band"] = np.select(conditions, choices, default="Junior")np.select() is the vectorised equivalent of if-elif-elif-else. The first matching condition wins. default handles the case where none of the conditions are True.
How do you apply a function to multiple columns at once?
# Apply same function to multiple columns:
cols = ["price", "cost", "margin"]
df[cols] = df[cols].apply(lambda x: round(x, 2))
# Or using vectorised operation:
df[cols] = df[cols].round(2)
# Apply different functions to different columns:
df.agg({"salary": "mean", "age": "median", "name": "count"})Applying a function directly to a DataFrame subset is cleaner than looping over columns. When a vectorised method exists (round, abs, etc.), always prefer it over apply().
EVIKA ACADEMY · PYTHON FOR DATA ANALYTICS
Want to master Python with live practice?
Join our Python for Data Analysis course — live classes in Noida and online across India.
Book Free Demo Class →