Use vectorized column arithmetic (df["col_a"] + df["col_b"]), np.where() / np.select() for conditional logic, or df.as(...) for method chaining whenever possible—falling back to df.apply(func, axis=1) (or zip(df["a"], df["b"]) list comprehension) only when your custom function requires complex Python objects, external API calls, or branching logic that cannot be vectorized.
Basic Example
import numpy as np
import pandas as pd
df = pd.DataFrame({
"price": [100.0, 250.0, 80.0],
"qty": [2, 1, 5],
"discount": [0.10, 0.0, 0.25],
})
# 1. Recommended (vectorized arithmetic — 100x+ faster than apply):
df["total"] = df["price"] * df["qty"] * (1.0 - df["discount"])
# 2. Recommended for conditional multi-column rules (np.where / np.select):
df["tier"] = np.where(df["total"] >= 200, "VIP", "Standard")
# 3. Fallback when custom non-vectorizable Python logic is genuinely required (`axis=1`):
def format_summary(row: pd.Series) -> str:
return f"{int(row['qty'])}x @ ${row['price']:.2f} -> ${row['total']:.2f} ({row['tier']})"
df["summary"] = df.apply(format_summary, axis=1)
print(df[["total", "tier", "summary"]])
# total tier summary
# 0 180.0 Standard 2x @ $100.00 -> $180.00 (Standard)
# 1 250.0 VIP 1x @ $250.00 -> $250.00 (VIP)
# 2 300.0 VIP 5x @ $80.00 -> $300.00 (VIP)
Key Details & Edge Cases
- Never forget
axis=1insidedf.apply(func, axis=1):df.apply(func)defaults toaxis=0(passing each column as aSeries), which immediately raisesKeyError: 'price'when your function indexesrow["price"]. Always specifyaxis=1to iterate across rows.
- Why
df.apply(..., axis=1)is slow (and howzip(...)beats it on Python logic):df.apply(func, axis=1)constructs a brand-newpd.Seriesobject for every single row in Python, adding massive per-row overhead on DataFrames over 10,000 rows.- When your function cannot be vectorized with NumPy/Pandas operators, iterating over
zip(df["price"], df["qty"])inside a list comprehension runs 5–15× faster thandf.apply(..., axis=1):df["summary"] = [f"{q}x @ ${p:.2f}" for p, q in zip(df["price"], df["qty"])]
- Returning multiple new columns from a single
apply(..., axis=1)call (result_type="expand"):- If your row function returns a tuple or list of values, pass
result_type="expand"to unpack them directly into multiple target columns:df[["net", "tax"]] = df.apply( lambda r: (r["total"] * 0.85, r["total"] * 0.15), axis=1, result_type="expand", )
- If your row function returns a tuple or list of values, pass
- Avoid
SettingWithCopyWarningwhen assigning to a filtered DataFrame:- If
dfcame from a slice (sub = df[df["qty"] > 1]), call.copy()first (sub = df[df["qty"] > 1].copy()) or usedf.assign(total=lambda d: d["price"] * d["qty"])to return a clean DataFrame without mutating in place.
- If
- Silent dtype upcasting trap inside
row(pd.Series) duringaxis=1:- Because
df.apply(..., axis=1)packs an entire row into a single 1DSeries, mixingintandfloatcolumns in the same DataFrame coercesrow["qty"]tofloat(2.0instead of2) inside your callback! Cast explicitly (int(row["qty"])) or usezip(...)to preserve native column dtypes.
- Because
Comparison of Multi-Column Row Computation Methods in Pandas
| Approach | Syntax Example | Speed (100k Rows) | Preserves Column Dtypes? | Best Used When |
|---|---|---|---|---|
| Vectorized Pandas / NumPy (Best) | df["c"] = df["a"] * df["b"] |
~1 ms (C/SIMD speed) | Yes | Arithmetic, string .str ops, .dt date math, and np.where() / np.select() conditions. |
df.as(...) |
df = df.assign(c=lambda d: d["a"] + d["b"]) |
~1 ms (vectorized) | Yes | Functional method chains (.query(...).assign(...).sort_values(...)) without intermediate variables. |
zip() List Comprehension |
df["c"] = [f(a, b) for a, b in zip(df["a"], df["b"])] |
~25 ms (fast Python loop) | Yes (exact per-column types) | Calling custom Python functions, regex/parsers, or external libraries across 2–4 columns. |
df.apply(fn, axis=1) |
df["c"] = df.apply(fn, axis=1) |
~400 ms (builds Series per row) |
No (coerces row to common dtype) | Small DataFrames (<10k rows) where a row function dynamically inspects many columns by name. |
You must log in or register to comment.
