Sub topic 13
Pitfalls and best practices
This chapter assumes you can write Python functions and lambdas, build a Series or DataFrame, and select columns and assign new ones. It also assumes you have met Series.map, Series.apply, DataFrame.apply and DataFrame.map. Here we collect the mistakes that come up most often and a short checklist for avoiding them.
Start with a vectorized expression
A vectorized expression works on whole columns at once, so pandas runs the loop in compiled code. apply and map call your Python function once per element, row or column. That is much slower on large data.
Ask these questions in order:
- Can arithmetic, comparison or a built-in method do it? Use that.
- Is it a lookup from old values to new values? Use
mapwith a dict. - Does the logic need your own Python code? Use
applyormap.
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
slow = df.apply(lambda row: row["price"] * row["qty"], axis=1)
fast = df["price"] * df["qty"]
print(slow.equals(fast))Both versions give the same numbers. The second is shorter and usually much faster, because the first builds a Series for every row.
Pitfall: missing values
map and apply pass NaN and None to your function. A string method such as str.upper fails on them. Use na_action="ignore" with map so missing values skip the function and stay missing.
import pandas as pd
s = pd.Series(["a", None, "c"])
print(s.map(str.upper, na_action="ignore"))With a dict, any value without a matching key also becomes NaN. If you want unmatched values to stay as they are, fill them afterwards:
import pandas as pd
s = pd.Series(["a", "b", "c"])
mapped = s.map({"a": "x", "b": "y"})
print(mapped.fillna(s))Pitfall: the wrong axis
DataFrame.apply defaults to axis=0, so your function receives each column. With axis=1 it receives each row. If your lambda uses row["price"] but you forgot axis=1, you get a KeyError or a confusing result. Check what the function receives by printing its argument on a small frame.
Pitfall: unexpected result shapes
What your function returns decides the shape of the result:
| Function returns | Result of `DataFrame.apply` |
|---|---|
| A scalar | A Series |
| A Series | A DataFrame |
| A list | Often a Series of lists, which is rarely what you want |
When you return a Series, its index becomes the column or row labels of the result. Give those labels explicit names, as in pd.Series({"min": ..., "max": ...}).
Pitfall: dtypes change
The result dtype comes from what your function returns. A function that returns integers for some rows and None for others gives a float or object column. After a transformation, check result.dtype and convert with astype if you need a specific type.
Pitfall: side effects and mutation
Your function should compute a value and return it. Do not modify global state or the input inside it. Pandas may call the function more than once on the first group or column in some versions, so side effects can repeat. If you forget return, every result is None.
Pitfall: applymap is deprecated
From pandas 2.1, DataFrame.applymap is deprecated. Use DataFrame.map for element-wise work. On older versions, applymap is the only choice.
Pitfall: groupby apply is slow and shape-sensitive
groupby(...).apply(func) calls your function once per group in Python. Prefer built-in aggregations such as max, min, sum and agg when they cover your case.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
g = df.groupby("team")["score"]
print(g.apply(lambda s: s.max() - s.min()))
print(g.max() - g.min())Both lines print the same range per team. The second uses only built-in methods.
Decision flow
Best practices checklist
- Try a vectorized expression before
apply. - Use
mapwith a dict for lookups, and fill unmatched values deliberately. - Set
na_action="ignore"when your function cannot handle missing values. - State
axisexplicitly when you useDataFrame.apply. - Return the same type from every call of your function.
- Test the function on a small sample first, then check the output dtype.
- Pass extra parameters as keyword arguments to
applyinstead of hard-coding them in a lambda.
Exercise
A column s = pd.Series(["a", None, "c"]) must be uppercased, and the missing value must stay missing. Your call s.map(str.upper) raises an error. What is the fix?
Show answer
Use s.map(str.upper, na_action="ignore"). Missing values are not passed to str.upper and remain NaN/None in the result. A vectorized alternative is s.str.upper(), which also leaves missing values alone.
Exercise
You wrote df["total"] = df.apply(lambda row: row["price"] * row["qty"], axis=1) on a frame with a million rows, and it is slow. Rewrite it and explain why the new version is faster.
Show answer
df["total"] = df["price"] * df["qty"]. This multiplies whole columns in compiled code, instead of calling a Python lambda and building a Series for each of the million rows.