User-Defined Functions
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Sooner or later a calculation does not exist as a built-in pandas method, and you write a function of your own. pandas
has six methods that take such a user-defined function (UDF): map, apply, pipe, filter, agg and
transform. They differ in what the function receives and what it must return, and choosing the wrong one gives
slow code or a confusing error. This page explains each of them, how they extend to groups and windows, what a UDF
costs and how to avoid that cost. It targets pandas 3.1 on Python 3.13 or 3.14 and was checked in October 2026; every
example was run with Python 3.13 and pandas 3.1.0 and the printed output is the real output.
The related pages are Group By, Rolling, Expanding and EWM, Essential Basic Functionality and Enhancing Performance. For the same idea in pure Python see Python functions, and in R the apply family.
The examples use a small temperature table:
import numpy as np
import pandas as pd
temp = pd.DataFrame(
{"NYC": [14, 21, 23], "LA": [22, 28, 31]},
index=pd.date_range("2026-07-01", periods=3),
)
print(temp)
NYC LA
2026-07-01 14 22
2026-07-02 21 28
2026-07-03 23 31
Think twice before writing a UDF
The official guide opens with a warning that applies to every example below: most tasks should be done with built-in methods or vectorised operations. A UDF has three costs:
-
Speed. pandas cannot optimise a Python function. It calls it once per element, per row, per column or per group, and every call goes through the interpreter, while a vectorised operation runs one compiled loop over the whole array.
-
Type inference. pandas has to guess the dtype of the result from what your function returns, and the guess can be wrong (an integer column becomes object because one call returned a string, for example).
-
Readability of the shape. Whether you get a Series, a DataFrame or a scalar back depends on the function, which makes the code harder to reason about.
UDFs are the right tool when the computation is domain-specific, when it calls an external library (a model’s
predict, a geocoder), or when a grouped operation does not fit a built-in. The figure of merit is not elegance but
what a measurement shows, as the benchmark further down illustrates.
The six methods at a glance
| Method | Function receives | Function returns | What pandas does |
|---|---|---|---|
|
One scalar |
One scalar |
Calls the function once per element |
|
A column as a Series |
A scalar, Series or list-like |
Calls the function once per column |
|
A row as a Series |
A scalar or a Series |
Calls the function once per row |
|
The whole Series or DataFrame |
Anything |
Calls the function once; just chaining syntax |
|
The whole object |
A boolean mask |
Keeps the rows where the mask is true |
|
A column (or the Series) |
A scalar |
Reduces every column to one value |
|
A column (or the Series) |
A result of the same length |
Returns an object with the original shape |
Most of them also exist on groupby, resample and the window objects (rolling, expanding, ewm), where
the "whole object" is one group or one window.
map: one value at a time
Series.map and DataFrame.map call the function on each element. The function receives a scalar and returns a
scalar. DataFrame.map replaces the old applymap, which was removed in pandas 3.0.
def to_fahrenheit(value):
return value * 9 / 5 + 32
print(temp.map(to_fahrenheit))
NYC LA
2026-07-01 57.2 71.6
2026-07-02 69.8 82.4
2026-07-03 73.4 87.8
Source: pandas.Series.map.
For a 3 by 2 table the function is called six times. Series.map also accepts a dict, a Series or a format string,
which is usually clearer and faster than a lambda for a lookup:
s = pd.Series([1, 2, 3])
print(s.map({1: "a", 2: "b"})) # unmapped values become NaN
print(s.map("x={}".format).tolist()) # a callable that is a format string
t = pd.Series(["a", None, "c"])
print(t.map(len, na_action="ignore").tolist()) # skip missing values
0 a
1 b
2 NaN
dtype: str
['x=1', 'x=2', 'x=3']
[1.0, nan, 1.0]
na_action="ignore" passes missing values through without calling the function, which avoids TypeError on a
None and keeps the missing value in the result. Extra arguments are passed as keywords:
s.map(func, key=value).
Series.apply on a Series behaves like map for a plain function but can also return a Series per element (which
becomes a DataFrame); map is the clearer choice for an element-wise function.
Source: pandas.Series.map and pandas.DataFrame.map.
apply: a column or a row at a time
DataFrame.apply calls the function once per column (axis=0, the default) or once per row (axis=1), passing a
Series. It is faster than map when the function itself is vectorised, because the work happens on whole columns.
def normalize(column):
return column / column.mean() # needs the whole column
print(temp.apply(normalize))
print(temp.apply(lambda col: col.max() - col.min())) # one number per column
NYC LA
2026-07-01 0.724138 0.814815
2026-07-02 1.086207 1.037037
2026-07-03 1.189655 1.148148
NYC 9
LA 9
dtype: int64
Source: pandas.DataFrame.apply.
With axis=1 the function receives a row as a Series whose index is the column labels:
def hotter(row):
return row["LA"] - row["NYC"]
print(temp.apply(hotter, axis=1))
def describe_row(row):
return pd.Series({"gap": row["LA"] - row["NYC"], "hotter": row.idxmax()})
print(temp.apply(describe_row, axis=1)) # a Series per row becomes a DataFrame
2026-07-01 8
2026-07-02 7
2026-07-03 8
Freq: D, dtype: int64
gap hotter
2026-07-01 8 LA
2026-07-02 7 LA
2026-07-03 8 LA
Source: pandas.DataFrame.apply.
Row-wise apply is the slowest of all (see the benchmark below) and it has a type trap: a row of a table with mixed
dtypes is a Series of one common dtype (object when strings are involved), so integers can become floats or objects on
the way in. Prefer column operations:
temp["LA"] - temp["NYC"] does the same job as hotter in microseconds.
The arguments of apply that change what the function sees or what comes back:
| Argument | Meaning |
|---|---|
|
0 passes columns, 1 passes rows |
|
Pass NumPy arrays instead of Series; faster when you do not need labels |
|
For |
|
|
|
|
|
Compile the function with numba; requires |
def scale(col, factor, offset=0):
return col * factor + offset
print(temp.apply(scale, args=(2,), offset=1))
print(temp.apply(lambda a: a.sum(), raw=True)) # a is a NumPy array
print(temp.apply(lambda r: [r.min(), r.max()], axis=1, result_type="expand"))
NYC LA
2026-07-01 29 45
2026-07-02 43 57
2026-07-03 47 63
NYC 58
LA 81
dtype: int64
0 1
2026-07-01 14 22
2026-07-02 21 28
2026-07-03 23 31
Source: pandas.DataFrame.apply.
Series.apply and Series.agg have a by_row argument. With the default by_row="compat" a function passed to
Series.apply is called on each element, like map; with by_row=False the function receives the whole Series
once, which lets it be vectorised:
s = pd.Series([1, 2, 3])
print(s.apply(lambda v: v * 10).tolist()) # element by element
print(s.apply(lambda ser: ser * 10, by_row=False).tolist()) # called once with the whole Series
[10, 20, 30]
[10, 20, 30]
Source: pandas.DataFrame.apply and pandas.Series.apply.
pipe: chain a function over the whole object
pipe hands the whole Series or DataFrame to your function. temp.pipe(f) is exactly f(temp); the point is
readability inside a method chain. Extra positional and keyword arguments go to the function, and a
(function, "keyword") tuple tells pipe which keyword receives the object when it is not the first parameter.
def add_ratio(df):
return df.assign(ratio=df["LA"] / df["NYC"])
def keep_columns(df, columns):
return df[columns]
result = (
temp
.pipe(add_ratio)
.pipe(keep_columns, columns=["ratio"])
.round(2)
)
print(result)
def scaled(factor, data):
return data * factor
print(temp.pipe((scaled, "data"), factor=2).iloc[0].tolist())
ratio
2026-07-01 1.57
2026-07-02 1.33
2026-07-03 1.35
[28, 44]
pipe does not make anything faster; it lets you mix built-in steps and your own functions in one readable chain
without temporary variables. It is also available on groupby and resample objects.
Source: pandas.DataFrame.pipe.
filter with a callable: select rows in a chain
DataFrame.filter(cond=...) (new in pandas 3.1) takes a function of the whole DataFrame that returns a boolean mask,
and keeps the rows where it is true. It is the chain-friendly form of boolean indexing, useful when the intermediate
object has no name:
hot_days = temp.assign(gap=temp["LA"] - temp["NYC"]).filter(cond=lambda d: d["gap"] > 7)
print(hot_days)
NYC LA gap
2026-07-01 14 22 8
2026-07-03 23 31 8
Without cond, filter selects labels with items, like or regex, which is a different operation (see
Indexing and Selecting). On a GroupBy, filter(func) is yet
another operation: the function is called once per group and returns a single boolean that keeps or drops the group (see
Group By).
Source: pandas.DataFrame.filter.
agg: reduce to a summary
agg calls the function once per column and expects a scalar. Several functions can be given as a list, with names or
as a dict:
def highest_jump(column):
return column.pct_change().max()
print(temp.agg(highest_jump))
print(temp.agg(["mean", "max", lambda c: c.max() - c.min()]))
NYC 0.500000
LA 0.272727
dtype: float64
NYC LA
mean 19.333333 27.0
max 23.000000 31.0
<lambda> 9.000000 9.0
A function that does not reduce (it returns more than one value per column) is not an aggregation; use apply
or transform instead.
Source: pandas.DataFrame.agg.
transform: keep the shape
transform is the broadcasting sibling of agg: the result must have the same length as the input. A function that
returns a scalar is not enough on a plain DataFrame; return a Series with the same index, for example a statistic
repeated per row:
def warm_up(column):
return pd.Series(column.max(), index=column.index)
print(temp.transform(warm_up))
try:
temp.transform(lambda col: col.sum())
except ValueError as exc:
print("ValueError:", exc)
NYC LA
2026-07-01 23 31
2026-07-02 23 31
2026-07-03 23 31
ValueError: Function did not transform
Source: pandas.DataFrame.transform.
On a GroupBy, transform is far more common because a scalar per group is broadcast to the group’s rows (see
Group By):
d = pd.DataFrame({"k": list("aabbb"), "v": [1, 2, 3, 4, 5]})
print(d.groupby("k")["v"].transform(lambda x: (x - x.mean()) / x.std()).round(3).tolist())
print(d.groupby("k")["v"].transform("max").tolist()) # built-in name: faster
[-0.707, 0.707, -1.0, 0.0, 1.0]
[2, 2, 5, 5, 5]
Source: pandas.DataFrame.transform.
UDFs on groups and windows
Group-wise and window-wise UDFs follow the same contracts, with the "object" being one group or one window.
print(d.groupby("k")["v"].apply(lambda x: x.max() - x.min())) # scalar per group
print(d.groupby("k").agg(spread=("v", lambda x: x.max() - x.min()))) # named aggregation
print(d.groupby("k").filter(lambda g: len(g) > 2)) # keep big groups
s = pd.Series([1.0, 3.0, 2.0, 6.0, 4.0])
print(s.rolling(3).apply(lambda w: w.max() - w.min(), raw=True).tolist())
k
a 1
b 2
Name: v, dtype: int64
spread
k
a 1
b 2
k v
2 b 3
3 b 4
4 b 5
[nan, nan, 2.0, 4.0, 4.0]
Rolling.apply and Expanding.apply call the function once per window, so a window of 1,000 points over a million rows
means a million Python calls. With raw=True the function receives a NumPy array (much cheaper than a Series), and
engine="numba" compiles it. A custom reduction on a rolling window is one of the cases where a UDF is hard to avoid;
see Rolling, Expanding and EWM.
What a UDF costs
The following timing compares a row-wise UDF, an element-wise map and the vectorised expression for the same ratio on
200,000 rows. The absolute numbers depend on your machine; the ratio between them is the lesson.
import time
rng = np.random.default_rng(0)
big = pd.DataFrame({"one": rng.random(200_000) + 1, "two": rng.random(200_000) + 1})
t0 = time.perf_counter()
a = big.apply(lambda r: 100 * (r["one"] / r["two"]), axis=1)
t1 = time.perf_counter()
b = 100 * (big["one"] / big["two"])
t2 = time.perf_counter()
c = big["one"].map(lambda v: v * 2)
t3 = time.perf_counter()
print(f"apply(axis=1): {t1 - t0:.3f} s")
print(f"vectorised: {t2 - t1:.5f} s")
print(f"map (1 col): {t3 - t2:.3f} s")
print("same result:", np.allclose(a, b))
apply(axis=1): 0.314 s
vectorised: 0.00029 s
map (1 col): 0.010 s
same result: True
Source: pandas user guide: UDF performance.
The official guide reports about 5.6 seconds for its row-wise UDF against four milliseconds for the vectorised form. In the run above the row-wise apply is about a thousand times slower than the
vectorised expression, and map over a single column is in between because the loop is over scalars, not rows.
The standard ladder for making a UDF fast is:
-
Use a built-in method or expression. Arithmetic, comparison,
where,clip, the.strand.dtaccessors,np.where,np.selectand the grouped reductions cover most needs. -
Vectorise with NumPy. Many scalar functions can be rewritten with
np.where,np.selector plain array arithmetic ondf["col"].to_numpy(). -
Compile with numba.
DataFrame.apply(..., raw=True, engine="numba"),Rolling.applyand the groupedaggandtransformacceptengine="numba", for functions written in numba’s subset of Python. -
Move the loop out of pandas (Polars, DuckDB, a compiled extension) when pandas is not the right tool; see Scaling to Large Datasets.
frame = pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [4.0, 5.0, 6.0]})
try:
print(frame.apply(lambda x: x.sum(), raw=True, engine="numba").tolist())
except ImportError as exc:
print("numba is not installed:", exc)
[6.0, 15.0]
numba is an optional dependency (the performance extra of pandas). The first call compiles the function, which
costs time, so it pays off on large inputs or when the same function is called many times. The function passed to
engine="numba" must be numba-compatible: NumPy arrays and scalars only, no pandas objects inside.
Common errors and surprises
-
ValueError: Function did not transform: The function passed totransformreturned a scalar or changed the length. Useaggfor a reduction or return a same-length result. -
Result is a Series of lists instead of a DataFrame. Return a
pd.Seriesfrom the function, or useresult_type="expand"withaxis=1. -
The dtype is object. Your function returned mixed types, or a row of a mixed-dtype table was converted to object. Cast afterwards with
astypeor avoid row-wiseapply. -
Side effects inside a UDF. Do not rely on how many times, or in which order, pandas calls the function; printing or appending to a list inside it gives results that depend on implementation details.
-
Mutating the argument. Return a new object (for example with
assign) instead of editing the argument in place; Copy-on-Write is the only mode in pandas 3, so a modified copy never writes back to the caller’s frame. -
applymapraisesAttributeError: it was removed in pandas 3.0; useDataFrame.map.
Decision guide
| Task | Method |
|---|---|
Transform each individual value |
|
Compute with a whole column, or a whole row with |
|
Chain several whole-table steps readably |
|
Keep rows that satisfy a condition, in a chain |
|
Reduce to one custom summary per column or per group |
|
Return a custom computation in the original shape (a group statistic on every row) |
|
Any of the above, but faster |
A vectorised expression first, then numba |