apply(), map() and Vectorization
Sometimes the built-in methods aren't enough and you need your own logic for each value or each row. pandas offers map(), apply() and DataFrame.map() for that. They're flexible, but they run ordinary Python code once per element, so they're slower than vectorized operations. This lesson shows when to use each.
Series.map(): translate values
map() transforms every value of a Series. Give it a dictionary to look values up, or a function to compute them:
import pandas as pd
sizes = pd.Series(["S", "M", "XL", "M", "L"])
print(sizes.map({"S": 36, "M": 40, "L": 44, "XL": 48}).to_list())
grams = pd.Series([250, 1200, 75])
print(grams.map(lambda g: f"{g / 1000:.2f} kg").to_list())
print(pd.Series(["S", "XXL"]).map({"S": 36, "M": 40}).to_list())[36, 40, 48, 40, 44]
['0.25 kg', '1.20 kg', '0.07 kg']
[36.0, nan]
Values missing from the dictionary become NaN, as XXL did.
Series.apply(): run a function
On a Series, apply() calls a function for every element, much like map() with a function. It's useful when the function takes extra arguments:
import pandas as pd
def shipping_cost(weight_kg, base=4.0, per_kg=1.5):
return base if weight_kg <= 1 else base + (weight_kg - 1) * per_kg
weights = pd.Series([0.4, 2.0, 5.5])
print(weights.apply(shipping_cost).to_list())
print(weights.apply(shipping_cost, per_kg=2.0).to_list())[4.0, 5.5, 10.75]
[4.0, 6.0, 13.0]
DataFrame.apply(): per column or per row
On a DataFrame, apply() passes whole columns to the function by default (axis=0), or whole rows with axis=1:
import pandas as pd
marks = pd.DataFrame({
"quiz": [7, 9, 6],
"essay": [14, 18, 11],
"exam": [52, 71, 48],
}, index=["Ivo", "Jun", "Kaya"])
print(marks.apply(lambda col: col.max() - col.min())) # per column
def grade(row):
total = row["quiz"] + row["essay"] + row["exam"]
return "A" if total >= 90 else "B" if total >= 70 else "C"
print(marks.apply(grade, axis=1)) # per rowquiz 3
essay 7
exam 23
dtype: int64
Ivo B
Jun A
Kaya C
dtype: object
Inside a row function, row["quiz"] reads that row's value.
DataFrame.map(): every cell
DataFrame.map() (called applymap() before pandas 2.1) applies a function to every single cell:
import pandas as pd
prices = pd.DataFrame({"basic": [4.5, 12.0], "premium": [9.0, 25.25]}, index=["tea", "lunch"])
print(prices.map(lambda p: f"€{p:,.2f}")) basic premium
tea €4.50 €9.00
lunch €12.00 €25.25
Prefer vectorized code
The row-wise grade function above works, but the same result can be computed on entire columns at once. That's both shorter and much faster on large data:
import numpy as np
import pandas as pd
marks = pd.DataFrame({
"quiz": [7, 9, 6],
"essay": [14, 18, 11],
"exam": [52, 71, 48],
}, index=["Ivo", "Jun", "Kaya"])
total = marks.sum(axis=1)
marks["grade"] = np.select([total >= 90, total >= 70], ["A", "B"], default="C")
marks["total"] = total
print(marks) quiz essay exam grade total
Ivo 7 14 52 B 73
Jun 9 18 71 A 98
Kaya 6 11 48 C 65
Here's a timing comparison on 200,000 rows. Exact timings vary by computer, so we only print which approach won:
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({"a": rng.random(200_000), "b": rng.random(200_000)})
t0 = time.perf_counter()
slow = df.apply(lambda r: r["a"] * 2 + r["b"], axis=1)
t1 = time.perf_counter()
fast = df["a"] * 2 + df["b"]
t2 = time.perf_counter()
print("same result:", np.allclose(slow, fast))
print("vectorized faster:", (t2 - t1) < (t1 - t0))same result: True
vectorized faster: True
| Need | Best tool |
|---|---|
| arithmetic, comparisons | operators on columns (df.a * 2) |
| if/else on values | np.where, np.select, clip, where |
| look up values in a table | map(dict) or merge |
| text operations | .str methods |
| truly custom logic | apply (accept the speed cost) |
Test yourself
What does s.map({"a": 1, "b": 2}) return for a value "c"?
- "c"
- 0
- NaN
- An error
In df.apply(f, axis=1), what does f receive?
- Each column
- Each row
- Each cell
- The whole DataFrame
Why is df["a"] * 2 usually preferred to df["a"].apply(lambda x: x * 2)?
- It gives a different result
- It is vectorized, so much faster
- apply cannot multiply
- It uses less code but is slower