Sub topic 5
Series.apply
This chapter assumes you can write a basic Python function or lambda, create a pandas Series, and assign a new column to a DataFrame. It covers what Series.apply passes to your function, what it returns, and the errors you are most likely to meet.
What Series.apply does
Series.apply(func) calls func once for each element of the Series. It collects the return values into a new Series that keeps the original index. The original Series is not changed.
import pandas as pd
s = pd.Series([4, 9, 16], index=["a", "b", "c"])
roots = s.apply(lambda x: x ** 0.5)
print(roots)The output keeps the labels a, b and c, with the values 2.0, 3.0 and 4.0 and dtype float64. pandas infers the dtype of the result from the returned values.
Writing the function
Your function receives one element at a time, as a plain Python or NumPy scalar. It can contain any logic, including branches that vectorized operators cannot express easily.
import pandas as pd
def grade(score):
if score >= 90:
return "A"
if score >= 75:
return "B"
return "C"
scores = pd.Series([95, 80, 60])
print(scores.apply(grade))You can pass a named function or a lambda. Use a named function when the logic needs more than one line, because it is easier to test and to read in a traceback.
What the return value decides
The type your function returns determines the shape of the result.
| Function returns | Result of apply |
|---|---|
| A scalar (number, string, bool) | A Series |
| A `pd.Series` | A DataFrame, one row per input element |
| A list or tuple | A Series whose elements are lists or tuples |
Returning a Series is useful for splitting one value into several columns:
import pandas as pd
s = pd.Series([1, 2, 3])
result = s.apply(lambda x: pd.Series({"square": x ** 2, "cube": x ** 3}))
print(result)The keys of the returned Series become the column names. Building a Series for every element is slow on large data, so use this form only on small inputs.
Common errors
Missing values reach your function
apply passes missing values to the function like any other element. A string method called on None or NaN raises an error.
import pandas as pd
s = pd.Series(["a", None, "c"])
def shout(x):
return x.upper() if isinstance(x, str) else x
print(s.apply(shout))Calling s.apply(str.upper) here fails with a TypeError, because None is not a string. Either handle missing values inside the function, as above, or use Series.map with na_action="ignore", which skips them.
Expecting the original to change
apply returns a new Series. Assign the result, for example df["grade"] = df["score"].apply(grade). Calling df["score"].apply(grade) alone computes the result and discards it.
Unexpected dtype
If your function returns mixed types, such as numbers for some elements and strings for others, the result has object dtype. Later arithmetic on it may fail or run slowly. Make the function return one consistent type.
Index mismatch on assignment
The result keeps the input index. If you assign it to a DataFrame column, pandas aligns on index labels, not position. This is correct when the Series came from that DataFrame. It produces NaN values if you filtered or reindexed in between.
Summary of the working model
- The function sees one element per call.
- The result has the same length and index as the input, unless you return Series objects, in which case the result is a DataFrame.
- Missing values are passed to your function.
- The input is never modified.
Exercise
A Series s = pd.Series([1, 2, 3]) is passed to s.apply(lambda x: [x, x * 10]). What type is the result, and how many elements does it have?
Show answer
The result is a Series with 3 elements. Each element is a list, for example [1, 10], because returning a list does not expand into columns. Only a returned pd.Series produces a DataFrame.