Sub topic 1
Passing your own functions to pandas
Prerequisites
This chapter assumes you can do the following:
- Write a Python function with
defand a shortlambdaexpression. - Create a pandas Series and DataFrame, and select a column with
df["name"]. - Assign a new column with
df["new"] = ....
The idea: pandas calls your function
Many pandas methods accept a function as an argument. You don't call the function yourself. You hand it to pandas, and pandas calls it for you, once for each piece of data. A function passed this way is often called a callable, which means any object Python can call with parentheses. Built-in functions, methods like str.upper, your own def functions, and lambdas are all callables.
The method you choose decides what "each piece" means. It also decides what shape the result has.
A first example
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map(str.upper))
print(s.map(lambda x: x * 2))The first call passes the existing method str.upper. Pandas calls it with "a", then "b", then "c", and returns a new Series A, B, C. The second call passes a lambda that repeats each string, so the result is aa, bb, cc. Your original Series s is unchanged.
Use a lambda for a quick one-line rule. Use a named def function when the logic needs several lines, a docstring, or reuse in more than one place.
Pass the function, don't call it
The most common beginner error is adding parentheses after the function name.
import pandas as pd
s = pd.Series(["a", "b", "c"])
# Wrong: str.upper() runs immediately, with no argument, and raises TypeError
# s.map(str.upper())
# Right: pass the function itself
print(s.map(str.upper))str.upper is the function. str.upper() is the result of calling it. Pandas needs the function so that it can call it later with real data.
The four methods in this tutorial
The rest of the tutorial covers four methods that take a callable. Each one sends a different piece of data to your function.
| Method | What your function receives | Typical result |
|---|---|---|
| `Series.map` | One element at a time | Series |
| `Series.apply` | One element at a time | Series (or a DataFrame, if your function returns Series) |
| `DataFrame.apply` | A whole column (`axis=0`) or a whole row (`axis=1`) as a Series | Series or DataFrame |
| `DataFrame.map` | One cell at a time | DataFrame |
DataFrame.map was called applymap before pandas 2.1. Later chapters explain each method and when to prefer one over another.
What your function must do
Pandas does not check your function's logic. It only calls the function and collects what comes back. Keep these rules in mind:
- The function must accept the type of data the method sends. A function written for a single number will fail if it receives a whole row.
- The function should return a value for every input. If it returns nothing in some branches, you get
Nonein the output. - The function should not depend on hidden state, such as a counter that changes with each call. Pandas does not promise a specific calling order for every method.
- Your function should not modify its input in place. Return a new value instead.
A speed warning
Calling a Python function once per element is slower than a vectorized operation. A vectorized operation works on a whole column at once, such as df["price"] * df["qty"]. These custom-function methods are a flexible tool, but not always the fastest one. Later in the tutorial you will see when to replace them with a vectorized expression.
Exercise
A colleague writes s.map(str.lower()) and gets a TypeError. What is wrong, and how do you fix it?
Show answer
The parentheses call str.lower immediately, with no string to work on, before pandas receives anything. Pass the function without parentheses: s.map(str.lower).
Exercise
Write a call that uses a lambda to add 1 to every element of s = pd.Series([1, 2, 3]). Does it change s?
Show answer
s.map(lambda x: x + 1) returns a new Series 2, 3, 4. It does not change s. To keep the result, assign it, for example s2 = s.map(lambda x: x + 1).