Sub topic 10
Custom transformations with apply
You have used vectorized operations, np.select, map, and the .str and .dt accessors to build columns. This chapter covers apply, which runs your own Python function on a column or on each row. It is the most flexible tool for building columns and usually the slowest, so the chapter also covers when to choose something else.
This chapter assumes you can write Python functions and lambdas, create a DataFrame, and select a column by name. The examples use this frame:
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})What apply does
apply calls a Python function many times and collects the results. The calls happen in a Python loop, not in the compiled code that makes vectorized operations fast. There are three common forms.
| Call | Function receives | Returns |
|---|---|---|
| `df["col"].apply(f)` | One value at a time | A Series, same length |
| `df.apply(f, axis=1)` | One row at a time, as a Series | A Series, or a DataFrame if `f` returns several values |
| `df.apply(f)` (default `axis=0`) | One whole column at a time, as a Series | One result per column |
The third form is for column-level summaries and is rarely how you build a new column. The first two are the ones you will use here.
Applying a function to one column
Use Series.apply when the logic for each value is easier to write as a function than as an expression.
def shipping_class(price):
if price < 5:
return "envelope"
if price < 20:
return "box"
return "freight"
df["shipping"] = df["price"].apply(shipping_class)
print(df) item price qty shipping
0 pen 1.5 10 envelope
1 book 12.0 3 box
2 lamp 30.0 2 freightPass the function itself, not a call to it. Write apply(shipping_class), not apply(shipping_class(...)). A lambda also works: df["price"].apply(lambda p: p * 2). That particular case is better written as df["price"] * 2.
Passing extra arguments
Extra parameters go in args (a tuple) or as keyword arguments. This avoids wrapping the function in a lambda.
def with_tax(price, rate, minimum=0.0):
return max(price * (1 + rate), minimum)
df["gross"] = df["price"].apply(with_tax, args=(0.2,), minimum=2.0)
print(df["gross"].tolist())[2.0, 14.399999999999999, 36.0]The pen's taxed price is 1.8, so the minimum of 2.0 wins. The second value shows normal floating-point rounding.
Applying a function across rows
Pass axis=1 to get one row at a time. Inside the function, row is a Series indexed by column names. This is the form to use when a result depends on several columns and no vectorized expression fits.
def describe(row):
return f"{row['qty']} x {row['item']} @ {row['price']:.2f}"
df["label"] = df.apply(describe, axis=1)
print(df["label"].tolist())['10 x pen @ 1.50', '3 x book @ 12.00', '2 x lamp @ 30.00']Forgetting axis=1 is the most common mistake. With the default axis=0, the function receives whole columns, and row["qty"] raises a KeyError or returns nonsense.
A row Series holds one dtype for all its values. If your columns mix numbers and strings, the row is an object Series, and numeric values may lose their NumPy types. This is another reason row-wise apply is slower and less predictable than column operations.
Returning several columns at once
If the function returns a tuple or list, result_type="expand" spreads the values across columns. Name the columns yourself, then join them back.
def split_cost(row):
total = row["price"] * row["qty"]
return total, row["qty"] >= 10
expanded = df.apply(split_cost, axis=1, result_type="expand")
expanded.columns = ["total", "bulk"]
df = df.join(expanded)
print(df[["item", "total", "bulk"]]) item total bulk
0 pen 15.0 True
1 book 36.0 False
2 lamp 60.0 FalseWithout result_type="expand", a function that returns a tuple gives you a Series of tuples, which you would have to unpack separately.
Missing values and apply
Unlike vectorized operations, apply does not skip NaN or None. Your function is called on them, and it must cope.
s = pd.Series(["a", None, "ccc"])
# s.apply(len) raises TypeError: object of type 'NoneType' has no len()
print(s.map(len, na_action="ignore"))0 1.0
1 NaN
2 3.0
dtype: float64Series.map accepts na_action="ignore", which leaves missing entries as NaN without calling your function. Series.apply has no such option, so either handle missing values inside the function (if pd.isna(x): return None) or use map for this case. For this particular task, s.str.len() is simpler still.
Choosing apply or an alternative
Reach for apply last. The usual order of preference is below.
Cases where apply is the right choice:
- The logic needs loops,
try/except, or calls to a library that accepts one value at a time, such as a parsing function or a regular expression with several branches. - Each row's result depends on several columns in a way that would take many nested
np.wherecalls to write. - The data is small enough that clarity matters more than speed.
Measuring the cost
The gap grows with row count. This comparison computes the same column both ways.
import timeit
import numpy as np
rng = np.random.default_rng(0)
big = pd.DataFrame({
"price": rng.uniform(1, 100, 200_000),
"qty": rng.integers(1, 20, 200_000),
})
t_apply = timeit.timeit(
lambda: big.apply(lambda r: r["price"] * r["qty"], axis=1), number=1
)
t_vec = timeit.timeit(lambda: big["price"] * big["qty"], number=1)
print(f"row apply: {t_apply:.2f}s, vectorized: {t_vec:.4f}s")Exact times depend on your machine, but the row-wise version is typically hundreds of times slower. Row-wise apply over 200,000 rows takes seconds. The vectorized product takes about a millisecond.
Common errors
- Missing
axis=1. The function gets columns, not rows, and fails or returns the wrong shape. - Calling the function when passing it.
apply(f(x))passes the result off, notf. - Assuming
NaNis skipped.applycalls your function on missing values, which often raisesTypeError. - Returning a Series from a Series-level apply.
df["a"].apply(lambda x: pd.Series([x, x]))builds a DataFrame, and assigning that to one column fails. Return a tuple and expand it, or build the columns separately. - Changing the row inside the function. Edits to
rowdo not reliably write back todf. Return the new value and assign the result. - Using
applyfor a plain lookup.df["item"].map({"pen": "P"})is clearer and faster.
Exercise
The frame has columns "price" and "qty". Write code that adds a column "flag" with the text "rush" when qty is at least 10 and price is under 5, and "normal" otherwise. First write it with df.apply, then say which approach you would choose in real code and why.
Show answer
With apply: df["flag"] = df.apply(lambda r: "rush" if r["qty"] >= 10 and r["price"] < 5 else "normal", axis=1). The vectorized version is df["flag"] = np.where((df["qty"] >= 10) & (df["price"] < 5), "rush", "normal"). Choose np.where. The condition is a plain comparison of two columns, so no custom function is needed, and it runs without a Python-level loop. Note the & operator and the parentheses, which vectorized conditions require.
Exercise
A Series s = pd.Series(["10", "20", None]) holds numbers as text with one missing value. What does s.apply(int) do, and how would you get [10.0, 20.0, NaN] without writing a loop?
Show answer
s.apply(int) raises a TypeError because int(None) is not allowed, since apply calls the function on the missing value. Use pd.tonumeric(s), which converts the strings and leaves the missing entry as NaN, giving float values 10.0, 20.0 and NaN. Alternatively, s.map(int, naaction="ignore") skips the missing entry, though to_numeric is the better fit for type conversion.