Sub topic 5
Series.apply
This chapter assumes you can write Python functions and lambdas, build a Series, and assign new columns. The previous chapters covered Series.map. This one covers Series.apply, which looks similar but gives you more control over arguments and result shape.
What Series.apply does
Series.apply(func) calls func once for each element of the Series. It collects the return values and builds a new Series with the same index as the original.
import pandas as pd
s = pd.Series([1, 2, 3, 4])
def label(n):
return "even" if n % 2 == 0 else "odd"
print(s.apply(label))The function is an ordinary Python function. pandas does not look inside it, so anything you can compute in Python is allowed. The cost is that pandas cannot speed it up either. Each element is a separate Python call.
Elements arrive as Python-level objects. Integers and floats come in as int and float. Datetime values arrive as pandas.Timestamp. Strings stay str.
import pandas as pd
dates = pd.Series(pd.to_datetime(["2026-01-15", "2026-03-02"]))
print(dates.apply(lambda ts: ts.day_name()))The function's parameter is a Timestamp, so you can use its methods directly.
The call sequence
The diagram shows what happens inside one call. The shape of the result depends on what your function returns.
Passing extra arguments
Your function often needs more than the element. apply forwards extra arguments in two ways. Use args= for a tuple of positional arguments. Use keyword arguments for the rest.
import pandas as pd
def add_tax(price, rate, rounding=2):
return round(price * (1 + rate), rounding)
prices = pd.Series([10.0, 20.0, 30.0])
print(prices.apply(add_tax, args=(0.2,)))
print(prices.apply(add_tax, rate=0.2, rounding=0))The first call passes 0.2 positionally, so it becomes rate. The second call uses keywords. Any keyword argument that apply does not recognize is forwarded to your function.
A lambda with a closure also works, but named parameters are easier to test and reuse:
import pandas as pd
prices = pd.Series([10.0, 20.0, 30.0])
rate = 0.2
print(prices.apply(lambda p: p * (1 + rate)))The closure reads rate from the surrounding scope when each call runs. If you change rate later and call apply again, you get a different result. Passing rate as an argument avoids that surprise.
What the function may return
The type of value your function returns decides the type of result:
| Function returns | Result |
|---|---|
| A scalar (number, string, bool, Timestamp) | A Series with the original index |
| A `pd.Series` | A DataFrame, one row per input element |
| A list, tuple, or dict | A Series whose elements are those objects |
| `None` for some elements | Those positions hold `None` or `NaN`, and the dtype may become `object` |
Returning a Series expands to columns
When every call returns a Series, the keys of those Series become column labels.
import pandas as pd
s = pd.Series([3, 4, 5])
out = s.apply(lambda n: pd.Series({"square": n ** 2, "cube": n ** 3}))
print(out)The output has columns square and cube and the original index of s. This is the main feature of apply that map does not offer in the same way. It is also slow, because pandas builds one small Series for every element. For anything beyond a few thousand rows, compute each column with a vectorized expression instead.
Returning a list keeps it as an object
import pandas as pd
words = pd.Series(["a b", "c d e"])
parts = words.apply(str.split)
print(parts)
print(parts.apply(len))parts is a Series of lists, so its dtype is object. The second call counts the items in each list. If you want the pieces as columns, words.str.split(expand=True) does that without calling Python once per row.
Dtype inference
pandas looks at the collected results and picks a dtype. If every result is an int, you get int64. If they mix numbers and strings, you get object.
import pandas as pd
s = pd.Series([1, 2, 3])
print(s.apply(lambda n: n * 2).dtype)
print(s.apply(lambda n: n / 2).dtype)
print(s.apply(lambda n: "big" if n > 1 else n).dtype)The first is an integer dtype and the second is float64. The third is object, because it mixes strings and integers. A mixed-type column is a common source of later errors, such as arithmetic on a column that is half text. Make your function return one type.
Missing values
Series.apply has no na_action parameter. Missing values are passed to your function like any other element. For a float Series, that means nan. For an object Series, it may be None or nan.
Many functions handle nan without trouble, because nan * 2 is nan. String methods do not.
import pandas as pd
s = pd.Series(["a", None, "c"])
def safe_upper(x):
return x.upper() if isinstance(x, str) else x
print(s.apply(safe_upper))Calling s.apply(str.upper) directly raises a TypeError, because None is not a string. You have three options:
- Check inside the function, as
safe_upperdoes. - Use
s.map(str.upper, na_action="ignore"), which skips missing values before calling the function. - Use the vectorized string accessor,
s.str.upper(), which propagates missing values on its own.
NumPy functions
You can pass a NumPy function such as np.sqrt to apply. The result is correct, but it is much slower than calling the function on the whole Series.
import numpy as np
import pandas as pd
s = pd.Series([1.0, 4.0, 9.0])
print(s.apply(np.sqrt))
print(np.sqrt(s))Both lines print the same values. NumPy functions already work on whole arrays, so the second form is the right one.
Comparing the cost
Here is a small benchmark you can run yourself. The exact numbers depend on your machine, but the gap between the two approaches is large.
import time
import numpy as np
import pandas as pd
s = pd.Series(np.arange(1_000_000, dtype="float64"))
start = time.perf_counter()
slow = s.apply(lambda x: x * 2 + 1)
t_apply = time.perf_counter() - start
start = time.perf_counter()
fast = s * 2 + 1
t_vec = time.perf_counter() - start
print(f"apply: {t_apply:.3f} s")
print(f"vectorized: {t_vec:.3f} s")
print(slow.equals(fast))The last line prints True, so both versions give the same values. The vectorized version runs in compiled code across the whole array, and the apply version makes a million Python calls.
apply compared with map
For a plain function over a Series, map and apply give the same result. The differences matter at the edges:
| Feature | `Series.map` | `Series.apply` |
|---|---|---|
| Accepts a dict or Series for lookup | Yes | No |
| `na_action="ignore"` | Yes | No |
| Extra arguments for the function | Not directly | `args=` and keyword arguments |
| Function may return a Series (expands to a DataFrame) | Not the intended use | Yes |
Use map for lookups and when you want missing values skipped. Use apply when your function needs parameters or when you want to return several values per element.
Common errors
- Function with the wrong signature. If
applyraisesTypeError: f() missing 1 required positional argument, you forgot to pass the extra argument. Useargs=or a keyword. - Returning a DataFrame or 2D array.
applyexpects a scalar or a Series from each call. A larger structure usually gives an error or anobjectcolumn. - Modifying the input. Your function receives elements, not a view of the Series. Changing a mutable element, such as a list stored in a cell, may change the original data. Return a new object instead.
- Printing instead of returning. A function that ends with
print(...)returnsNone, so the result is a Series ofNone. - Assuming a fixed dtype. Check
result.dtypeafterapplywhen later code depends on numbers or strings.
Practice
Exercise
A Series s = pd.Series([5, 10, 15]) and a function def scale(x, factor, offset=0): return x * factor + offset. Write the two calls that give the result [11, 21, 31], one passing factor with args= and one using only keyword arguments.
Show answer
With args: s.apply(scale, args=(2,), offset=1). With keywords only: s.apply(scale, factor=2, offset=1). Both compute x * 2 + 1 for each element, which gives 11, 21, 31.
Exercise
names = pd.Series(["ann", None, "bob"]). Calling names.apply(str.title) raises a TypeError. Give two ways to get ["Ann", None, "Bob"] while keeping the missing value.
Show answer
Option 1: names.map(str.title, na_action="ignore"), which skips the missing value. Option 2: names.apply(lambda x: x.title() if isinstance(x, str) else x), which checks the type inside the function. The vectorized names.str.title() also works and keeps the missing value.
Exercise
What type of object does pd.Series([1, 2]).apply(lambda n: pd.Series({"a": n, "b": n * 10})) return, and what are its column labels?
Show answer
It returns a DataFrame with two rows, one per input element, and columns "a" and "b". Each returned Series becomes one row, and its index labels become the column labels.