Sub topic 13
Pitfalls and best practices
This chapter collects the mistakes that show up most often when you run your own functions over pandas data, and the habits that avoid them. It assumes you know Series.map, Series.apply, DataFrame.apply with axis, and DataFrame.map from the earlier chapters. It also assumes pandas 2.1 or later, and you should be comfortable with basic Python functions and lambdas.
Reach for a vectorized expression first
apply and map call your Python function once per element, row, or column. Pandas cannot speed up that loop. A vectorized expression such as df["price"] * df["qty"] runs in compiled code over the whole array.
The usual cost is 10 to 100 times slower for row-wise apply on large frames. You can measure it yourself:
import time
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
df = pd.DataFrame({
"price": rng.random(200_000) * 100,
"qty": rng.integers(1, 10, 200_000),
})
start = time.perf_counter()
slow = df.apply(lambda row: row["price"] * row["qty"], axis=1)
t_apply = time.perf_counter() - start
start = time.perf_counter()
fast = df["price"] * df["qty"]
t_vector = time.perf_counter() - start
print(f"apply: {t_apply:.3f} s")
print(f"vectorized: {t_vector:.5f} s")
print(slow.equals(fast))The exact timings depend on your machine. The gap is large, and slow.equals(fast) prints True.
Before writing apply, check whether one of these covers the job:
| Task | Vectorized tool |
|---|---|
| Arithmetic across columns | `df["a"] * df["b"]` |
| Conditional values | `np.where`, `Series.where`, `Series.mask` |
| Several conditions | `np.select` |
| String work | the `.str` accessor, such as `s.str.upper()` |
| Date parts | the `.dt` accessor |
| Value substitution | `Series.replace` or `Series.map` with a dict |
| Binning | `pd.cut`, `pd.qcut` |
Use apply when the logic is genuinely not expressible this way. Examples are parsing an irregular string, calling a library function that accepts one scalar, or branching logic that is hard to write as array operations.
Missing values reach your function
With Series.map, na_action="ignore" keeps missing values away from your function. Series.apply has no such option, so None and NaN arrive in your function as they are. A function that assumes strings fails on them:
import pandas as pd
s = pd.Series(["a", None, "c"])
try:
s.apply(str.upper)
except TypeError as err:
print("TypeError:", err)
def shout(x):
return x.upper() if isinstance(x, str) else x
print(s.apply(shout))
print(s.str.upper())The last line shows the best fix for this case. The .str accessor already skips missing values, so no custom function is needed.
Numeric NaN is gentler. NaN * 2 is NaN, so arithmetic functions often pass through without error. A function with a comparison such as x > 0 returns False for NaN, which silently classifies missing data as "not positive". Decide explicitly what a missing value should produce.
A dict passed to map drops unmatched values
When map receives a dict, any value without a matching key becomes NaN. This is useful for strict lookups and a trap for partial recoding.
import pandas as pd
s = pd.Series(["a", "b", "z"])
mapping = {"a": "x", "b": "y"}
print(s.map(mapping))
print(s.map(mapping).fillna(s))
print(s.replace(mapping))The first result turns "z" into NaN. The second restores unmapped values with fillna(s). The third uses replace, which leaves unmatched values alone from the start. Pick map when every value must be in the lookup, and replace when only some should change.
A related effect is that a column of integers can become floats after map produces even one NaN, because integer NumPy dtypes cannot hold missing values.
Row-wise apply changes your dtypes
With axis=1, each row is a single Series. A Series has one dtype, so pandas finds a common type for the row's values. Mixed columns therefore get converted:
import pandas as pd
mixed = pd.DataFrame({"name": ["a", "b"], "qty": [1, 2]})
print(mixed.apply(lambda row: str(row.dtype), axis=1))
numeric = pd.DataFrame({"qty": [1, 2], "price": [1.5, 2.5]})
print(numeric.apply(lambda row: str(row.dtype), axis=1))The first frame produces object rows, so integers are no longer NumPy integers inside your function. The second produces float64, so qty arrives as a float. Code that depends on integer behavior, such as bit operations, integer division, or exact comparisons on large values, can then give surprising results.
To avoid this, select only the columns you need before applying. For example, use df[["qty", "price"]].apply(...). Better still, use a vectorized expression.
Keep the return shape consistent
The shape of the result depends on what your function returns. Mixing return types across calls makes the output hard to predict.
import pandas as pd
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
as_lists = df.apply(lambda r: [r["a"] + r["b"], r["a"] * r["b"]], axis=1)
print(as_lists)
expanded = df.apply(
lambda r: [r["a"] + r["b"], r["a"] * r["b"]],
axis=1,
result_type="expand",
)
print(expanded)
as_frame = df.apply(
lambda r: pd.Series({"total": r["a"] + r["b"], "product": r["a"] * r["b"]}),
axis=1,
)
print(as_frame)The first call returns a Series whose elements are Python lists. That is rarely what you want. result_type="expand" spreads the lists into columns numbered 0 and 1. Returning a Series gives named columns, which is usually clearest.
Follow these rules:
- Return the same kind of value on every call: always a scalar, or always a Series with the same index.
- Avoid returning
Noneon some branches. It becomes a missing value and can change the result's dtype. - Name the output columns by returning a Series with an index, not a bare list.
Prefer named functions to long lambdas
A lambda is fine for a one-line expression. Once a function has branches, it needs a name, a docstring, and a test of its own.
import pandas as pd
def shipping_band(weight_kg):
"""Return a shipping band label for a weight in kilograms."""
if pd.isna(weight_kg):
return "unknown"
if weight_kg < 1:
return "light"
if weight_kg < 10:
return "standard"
return "heavy"
weights = pd.Series([0.4, 3.0, None, 25.0])
print(weights.map(shipping_band))You can test shipping_band without any DataFrame, which makes bugs easier to find. Handling NaN inside the function with pd.isna is also clearer than hoping the data is clean.
A function that does this kind of branching on a whole column can often be replaced by pd.cut:
import pandas as pd
weights = pd.Series([0.4, 3.0, None, 25.0])
bands = pd.cut(
weights,
bins=[0, 1, 10, float("inf")],
labels=["light", "standard", "heavy"],
right=False,
)
print(bands)pd.cut is vectorized and leaves missing weights as NaN. Use map with the named function when the rules are too irregular for bins.
Do not rely on side effects
Your function should compute a value from its input and return it. Avoid appending to outside lists, changing global counters, or modifying the row you were given. Pandas may copy the data it passes in, so mutations can be lost, and the number and order of calls is not something to depend on. If you need logging or counting, compute the result first and do the bookkeeping afterward.
Group-wise work: use agg and transform first
groupby(...).apply is the most flexible grouped tool and also the slowest. It calls your function once per group, and the combined output shape depends on what the function returns. Prefer these when they fit:
aggwhen each group reduces to one value, for exampleg["score"].agg("max").transformwhen the result keeps the original row count, for example a per-group z-score.
import pandas as pd
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
g = df.groupby("team")["score"]
df["z"] = (df["score"] - g.transform("mean")) / g.transform("std")
print(df)
spread = df.groupby("team")[["score"]].apply(
lambda part: part["score"].max() - part["score"].min()
)
print(spread)The z column uses only built-in reductions, with no Python function per group. In the apply example, selecting [["score"]] before apply keeps the grouping column out of each group frame. In recent pandas versions, DataFrameGroupBy.apply that operates on the grouping columns is deprecated and emits a warning. Selecting the columns you need, or passing include_groups=False, avoids the warning.
Version and naming changes
DataFrame.applymapis deprecated since pandas 2.1. UseDataFrame.map. Code that must run on older pandas needs a version check, or you can pin a minimum pandas version.DataFrame.mapapplies your function to every cell. It has no row or column context, so it cannot compare columns.raw=TrueinDataFrame.applypasses NumPy arrays instead of Series. It is faster, but you lose labels, so use positional indexing likerow[0].
A short checklist
- Can a built-in, accessor,
np.where,replace, orpd.cutdo it? Use that. - Decide what a missing value should produce, and handle it in the function or with
na_action="ignore"onmap. - Select only the columns you need before
apply(axis=1), to avoid dtype conversion. - Return the same shape every time, and prefer a Series with named index labels.
- Give non-trivial logic a named, testable function.
- For groups, try
aggandtransformbeforeapply. - Time a small sample before running
applyon millions of rows.
Exercise
A Series s = pd.Series(["a", "b", "z", None]) and a dict m = {"a": "x", "b": "y"}. s.map(m) returns x, y, NaN, NaN. Write one expression that recodes "a" and "b" and keeps "z" and the missing value unchanged. Then name one reason to prefer it to s.map(m).fillna(s).
Show answer
Use s.replace(m). It only substitutes keys that appear in the dict and leaves everything else untouched, including None. The map(...).fillna(s) version also works for "z". However, fillna(s) cannot tell an unmapped value from a value that was mapped to NaN on purpose, and it takes two steps.
Exercise
You have df = pd.DataFrame({"label": ["a", "b"], "qty": [1, 2], "price": [1.5, 2.5]}). A colleague writes df.apply(lambda r: r["qty"] * r["price"], axis=1). Explain what dtype each row has inside the function, then rewrite the code so it avoids the issue.
Show answer
Each row mixes a string with numbers, so the row Series has dtype object. The numbers are no longer stored as NumPy numeric types in the row. The best rewrite is vectorized: df["qty"] * df["price"]. If a function is truly needed, select only the numeric columns first, as in df[["qty", "price"]].apply(func, axis=1). The rows then have float64 dtype.
Exercise
For a DataFrame with columns team and score, you want a new column holding each score minus its team's mean score. Which groupby method fits better, apply or transform, and why?
Show answer
transform. The result must have the same length and index as the original rows. df["score"] - df.groupby("team")["score"].transform("mean") does it with built-in reductions and no Python function per group. apply would call a function for every group and would need extra care to align the combined result back to the original rows.