Sub topic 10
Custom transformations with apply
This chapter assumes you can build a DataFrame, select a column by name, and write a short Python function or lambda. It also assumes you know that arithmetic on columns is vectorized, meaning it runs on all rows at once.
When apply is the right tool
Vectorized operations, np.select, map, and the .str and .dt accessors cover most column work. Use apply when the logic for one value or one row is too tangled for those tools. Examples are calling a helper function, parsing an odd format, or branching on several columns with different rules.
apply takes a function and calls it once per element or per row. That is a Python-level loop, so it is more flexible than the vectorized tools and also slower.
Series.apply: one value at a time
On a single column, apply passes each value to your function and collects the returns into a new Series.
import pandas as pd
df = pd.DataFrame({
"item": ["pen", "book", "lamp"],
"price": [1.5, 12.0, 30.0],
"qty": [10, 3, 2],
})
def shipping_label(name):
if name.startswith("l"):
return "fragile"
return "standard"
df["shipping"] = df["item"].apply(shipping_label)
print(df)The function receives a plain Python value (here a string). The result is aligned to the original rows, so assigning it to a new column works directly.
DataFrame.apply with axis=1: one row at a time
When the result depends on several columns, apply the function to the whole frame with axis=1. Each call receives one row as a Series, indexed by column name.
def describe(row):
total = row["price"] * row["qty"]
return f"{row['item']}: {total:.2f}"
df["summary"] = df.apply(describe, axis=1)
print(df["summary"])Without axis=1, pandas uses axis=0 and passes each column to the function instead. That is a common source of confusing KeyError messages, because the function looks up "price" inside a column of values.
Common errors
- Using apply where a vectorized form exists.
df["price"].apply(lambda p: p * 2)gives the same answer asdf["price"] * 2but runs far slower on large frames. - Forgetting missing values. Your function is called on
NaNtoo. A call likename.startswith("l")raisesAttributeErrorwhennameisNaN, so check withpd.isna(value)first. - Returning inconsistent types. If some calls return numbers and others return strings, the column ends up with
objectdtype and later arithmetic fails. - Mutating the row. Changes inside the function do not reliably write back to the DataFrame. Return a value and assign it.
Choosing between the options
| Situation | Better choice |
|---|---|
| Arithmetic or comparison on columns | Vectorized operators |
| Several ordered conditions | `np.select` |
| Lookup from a dictionary | `map` |
| Text cleanup | `.str` accessor |
| Custom logic per value or per row | `apply` |
Exercise
A DataFrame has columns "first" and "last" holding names. You write df["full"] = df.apply(lambda r: r["first"] + " " + r["last"]) and get a KeyError. What is wrong, and what is a faster alternative?
Show answer
apply defaults to axis=0, so the lambda receives whole columns and r["first"] fails. Add axis=1 to pass rows. A faster approach avoids apply entirely: df["full"] = df["first"] + " " + df["last"].