Call df["col"].apply(func) directly on the target Series (do not pass axis=1, since a single column is 1-dimensional) to invoke a custom Python function element-by-element across every value in that column, passing extra positional or keyword arguments via args=(...,) or keyword arguments (df["col"].apply(func, multiplier=2)), and preferring built-in vectorized Series operations (.str, .dt, arithmetic, np.where) whenever available because .apply() runs a Python-level loop rather than C-vectorized array operations.
Basic Example
import pandas as pd
df = pd.DataFrame({
"product": [" laptop pro ", "wireless mouse", "usb-c hub"],
"price": [1200.0, 25.0, 45.0],
})
# 1. Recommended for custom Python logic: Call `.apply()` directly on the Series `df["col"]`
def classify_tier(price: float, threshold: float = 100.0) -> str:
return "Premium" if price >= threshold else "Standard"
df["tier"] = df["price"].apply(classify_tier, threshold=50.0)
# 2. Using a concise lambda expression for simple inline transformations:
df["taxed_price"] = df["price"].apply(lambda p: round(p * 1.15, 2))
# 3. Prefer vectorized `.str` / arithmetic over `.apply()` when a native accessor exists:
df["clean_product"] = df["product"].str.strip().str.title()
print(df)
# Output:
# product price tier taxed_price clean_product
# 0 laptop pro 1200.0 Premium 1380.00 Laptop Pro
# 1 wireless mouse 25.0 Standard 28.75 Wireless Mouse
# 2 usb-c hub 45.0 Standard 51.75 Usb-C Hub
Key Details & Edge Cases
- Never pass
axis=1toSeries.apply()(TypeError):- Unlike
DataFrame.apply(func, axis=1)(which iterates over rows),df["col"]is a 1DSeries. Passingdf["col"].apply(func, axis=1)raisesTypeError: <lambda>() got an unexpected keyword argument 'axis'because Series.apply()forwards extra keyword arguments directly to your functionfunc.
- Unlike
- Handling
NaN/Nonemissing values inside.apply():Series.apply()passesNaN(asfloat('nan')) orNonedirectly into your function, which often causesAttributeError: 'float' object has no attribute 'split'on string columns. Either guard inside your function (if pd.isna(x): return x), chain.dropna().apply(func)(assigning back aligns by index automatically!), or usena_action="ignore"inSeries.map(func, na_action="ignore").
- Returning multiple columns from a single-column
.apply():- If your function returns a
tuple(e.g.,(first, last)),df["full_name"].apply(split_name)produces a single Series of tuples. Wrap the return value inpd.Series((first, last))(or convert withpd.DataFrame(s.tolist(), index=df.index)) to expand it directly into two separate DataFrame columns:df[["first", "last"]] = df["full_name"].apply(lambda s: pd.Series(s.split(" ", 1)))
- If your function returns a
Series.apply()vs.Series.map()(dictionary lookups andna_action="ignore"):Series.map()accepts both callables and lookup dictionaries/Series (df["code"].map({"US": "United States", "PK": "Pakistan"})), plus supportsna_action="ignore"to skipNaNvalues without calling your function—whereasSeries.apply()only accepts callables and supports passing extra*args/**kwargstofunc.
- Avoid
df[["col"]].apply(...)(double brackets) unless you intentionally want a 1-column DataFrame:- Double brackets
df[["col"]]return a 2DDataFrame, so.apply(func)passes the entire columnSeriesat once tofuncinstead of individual cell values. Use single bracketsdf["col"].apply(func)for element-wise value transformations.
- Double brackets
Comparison of Single-Column Transformation Methods in Pandas
| Method | Execution Speed | Accepts Extra *args / **kwargs? |
Accepts Dict / Series Mapping? | Best Used When |
|---|---|---|---|---|
df["col"].apply(func, **kwargs) (Recommended for custom functions) |
Moderate (Python per-element loop) | Yes (args=(...) or kwarg=val) |
No (callables only) | Applying custom Python business logic, regex parsers, or multi-argument functions to each cell. |
df["col"].map(arg, na_action="ignore") |
Moderate (Python loop; fast for dict lookups) | No (single-argument callable or mapping) | Yes (dict or pd.Series) |
Translating category codes via a dictionary or running a 1-arg function while skipping NaN values. |
Vectorized .str / .dt / NumPy (np.where, np.select) |
10x–100x Faster (C/Cython array ops) | N/A | N/A | Arithmetic, string cleaning (df["col"].str.lower()), date extraction, and conditional branching. |
df["col"].transform(func) |
Moderate to Fast | Yes | No | Pipeline chaining where output shape/index is strictly guaranteed to match the input Series length. |
You must log in or register to comment.
