apply, and When Not To

A general escape hatch that is slower than the thing it usually replaces.

apply runs your function per value

It is flexible and it is a Python loop underneath, so it costs far more than the vectorised version when one exists.

import pandas as pd

s = pd.Series([1, 2, 3])
print(s.apply(lambda x: x * 2).tolist())
print((s * 2).tolist())

Reach for the built-in first

Arithmetic, comparisons, .str methods and .dt methods all have vectorised forms. apply earns its place when the logic genuinely is not expressible that way.

import pandas as pd

names = pd.Series([" Ada ", "GRACE"])
print(names.str.strip().str.lower().tolist())

Exercise

Try It Yourself

Write clean_names(names) that takes a Series of names and returns a list with the spaces trimmed and everything lowercased, without using apply.

Press Run to see output

Check Your Understanding