Sub topic 7
When apply, map, and string methods are the right tool
This chapter assumes you can run a pandas pipeline, use perf_counter for timing, and know why a Python-level loop over rows is slow. Here you learn when apply, map, and .str methods are acceptable, and when they hide a slow loop.
What these methods really do
Series.apply(func) and Series.map(func) call a Python function once per element. That is a Python loop with a friendlier name. It is faster than iterrows because it skips building a row object for each row. It is still much slower than a vectorized expression.
DataFrame.apply(func, axis=1) is worse. It builds a Series for every row and calls your function on it. Treat it as a row loop.
String methods are a special case. For the default object dtype, .str methods also loop in Python internally. Their benefit is not raw speed. They skip missing values safely, and they are easier to read.
Choosing the tool
map for lookups
When you translate codes into values, pass a dictionary to map. Pandas does the lookup through an index, not by calling a Python function per row.
import pandas as pd
orders = pd.DataFrame({"code": ["A", "B", "A", "C"], "amount": [100.0, 50.0, 80.0, 20.0]})
rates = {"A": 0.10, "B": 0.20}
orders["rate"] = orders["code"].map(rates)
orders["rate"] = orders["rate"].fillna(0.0)
orders["tax"] = orders["amount"] * orders["rate"]
print(orders)Keys missing from the dictionary become NaN. Here code C has no rate, so fillna supplies a default. Forgetting this step is a common source of silent NaN values.
String methods and missing values
Use .str for text cleaning instead of apply with a lambda.
import pandas as pd
names = pd.Series([" Oslo ", "lima", None, "PUNE"])
clean = names.str.strip().str.title()
print(clean.tolist())
# The apply version fails on the missing value:
try:
names.apply(lambda x: x.strip().title())
except AttributeError as err:
print("apply failed:", err)None (or NaN) has no strip method, so the lambda raises AttributeError. The .str version returns NaN for that entry and continues. You can chain .str calls, and .str.contains, .str.replace, and .str.split follow the same pattern.
apply for logic with no vectorized form
Some logic really is custom, such as parsing a messy format with several branches. Use Series.apply on one column, keep the function small, and measure it.
import pandas as pd
raw = pd.Series(["12 kg", "3.5kg", "800 g", "n/a"])
def to_kg(text):
text = text.strip().lower()
if text.endswith("kg"):
return float(text[:-2])
if text.endswith("g"):
return float(text[:-1]) / 1000
return float("nan")
weights = raw.apply(to_kg)
print(weights.tolist())Before you accept this, check whether pandas can do the same work in a vectorized way. Here raw.str.extract(r"([\d.]+)\s*(kg|g)") pulls out the number and the unit. A vectorized np.where on the unit can then convert grams. The apply version is easier to read. The .str version is usually faster on large data. Time both with perf_counter, and compare their output as the previous chapter showed.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `AttributeError` inside `apply` | A missing value reached your function | Use `.str` methods, or handle `NaN` in the function |
| New column is all `NaN` after `map` | Dictionary keys differ in type or case from the data | Check `df["code"].unique()` against the keys |
| `.str` raises `AttributeError: Can only use .str accessor with string values` | The column is numeric or mixed | Convert with `astype("string")` first |
| `apply(axis=1)` is the slowest step in the profile | It is a row loop | Rewrite with column arithmetic, `np.where`, or `map` |
Exercise
A column status holds the strings "active", "inactive", and some missing values. You write df["status"].apply(lambda s: s.upper()) and it raises an error. Name the cause and give a fix that keeps the missing values as NaN.
Show answer
The lambda is called on the missing value, which is a float NaN or None and has no upper method, so it raises AttributeError. Use df["status"].str.upper(), which skips missing values and returns NaN for them.
Exercise
You have a column tier with values "gold", "silver", and "bronze", and a dict {"gold": 0.3, "silver": 0.2, "bronze": 0.1}. Write one line that adds a discount column, and explain why it is better than apply(axis=1).
Show answer
df["discount"] = df["tier"].map({"gold": 0.3, "silver": 0.2, "bronze": 0.1}). It looks values up through an index and works on a single column. apply(axis=1) builds a Series for every row and calls a Python function each time.