apply() (Pandas)

apply() runs a function along an axis of a DataFrame or over every element of a Series. It is the flexible escape hatch for transformations that don't have a built-in vectorized method.

Pandas

On a Series, apply(func) calls func once per element and returns a new Series of the results. On a DataFrame, df.apply(func) calls func once per column by default (axis=0), or once per row with axis=1, passing each column/row in as a Series.

apply is the most general way to transform data, but it is also the slowest because it loops in Python rather than running compiled vectorized code. Reach for a built-in vectorized operation (arithmetic, str methods, where) first; use apply when no such operation exists.

For element-wise work across an entire DataFrame, use df.map() (the per-element method); apply with axis=1 is for logic that needs several columns of a row at once.

Syntax

s.apply(func)  |  df.apply(func, axis=0)

Examples

Python

import pandas as pd
s = pd.Series([1, 2, 3])
print(s.apply(lambda x: x * 10))

Output:

0    10
1    20
2    30
dtype: int64

Learn it in a lesson

See also

Back to the Dictionary