Sub topic 1
Passing your own functions to pandas
pandas lets you hand it a function and have it run that function over your data. Series.map, Series.apply, DataFrame.apply and DataFrame.map all work this way, and so do assign, loc, pipe and sort_values. This chapter gives the working model they share. The later chapters cover each method in detail.
Prerequisites
This chapter assumes you can do the following:
- Write a Python function with
defand a shortlambdaexpression. - Create a pandas
SeriesandDataFrameand select a column withdf["name"]. - Assign a new column with
df["new"] = ....
Examples run on pandas 2.1 or later. Where a method name changed, the text says so.
Functions are values
In Python a function is an object. You can store it in a variable, put it in a list, or pass it to another function. The name of a function and a call to it are different things:
def shout(text):
return text.upper() + "!"
print(shout) # the function object itself
print(shout("hi")) # the result of calling it: HI!shout is the function. shout("hi") is a string, the result of running it. When pandas asks for a function, you give it the first form, with no parentheses. pandas calls the function later, as many times as it needs.
import pandas as pd
s = pd.Series(["a", "b", "c"])
print(s.map(shout))The output is A!, B! and C!. pandas called shout three times, once per element, and collected the return values into a new Series. Your function never loops over the data. pandas does the looping and you describe the work for one unit.
What counts as a callable
pandas accepts any callable, meaning any object you can put parentheses after. The common kinds are:
| Kind | Example |
|---|---|
| Named function | `s.map(shout)` |
| Lambda | `s.map(lambda x: x * 2)` |
| Built-in function | `s.map(len)` |
| Unbound method | `s.map(str.upper)` |
| Partial application | `s.apply(partial(add_tax, rate=0.2))` |
| Object with `__call__` | `s.map(MyTransformer())` |
Use a named function when the logic needs a docstring, a test, or more than a line or two. Use a lambda for a short expression you won't reuse.
functools.partial fixes some arguments of a function in advance and gives you a new callable. It is useful when a method calls your function with one argument but your function needs more:
from functools import partial
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
with_tax = prices.map(partial(add_tax, rate=0.2))
print(with_tax)Series.apply can also forward keyword arguments directly, which a later chapter covers.
The working model
Every method in this tutorial follows the same three steps:
- pandas splits your data into units. The unit depends on the method.
- pandas calls your function once for each unit.
- pandas combines the return values into a result.
Steps 1 and 3 are where the methods differ. Step 2 is the same everywhere.
The unit determines what your function receives as its argument. You can check this by passing a function that records the type of whatever it is given and returns it unchanged:
import pandas as pd
def probe(call):
seen = []
def spy(x):
seen.append(type(x).__name__)
return x
call(spy)
return seen
s = pd.Series([1, 2, 3])
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(probe(s.map)) # ['int', 'int', 'int']
print(probe(s.apply)) # ['int', 'int', 'int']
print(probe(df.apply)) # ['Series', 'Series']
print(probe(lambda f: df.apply(f, axis=1))) # ['Series', 'Series']
print(probe(df.map)) # ['int', 'int', 'int', 'int']The results show what each method treats as a unit:
| Method | Your function receives | Calls for the data above |
|---|---|---|
| `Series.map(f)` | one element | one per element |
| `Series.apply(f)` | one element | one per element |
| `DataFrame.apply(f)` | one column, as a Series | one per column |
| `DataFrame.apply(f, axis=1)` | one row, as a Series | one per row |
| `DataFrame.map(f)` | one cell | one per cell |
DataFrame.map exists from pandas 2.1. In earlier versions the same operation is called applymap, which is deprecated in newer releases.
Once you know what the unit is, you can write the function's signature before you write its body. A function for df.apply(f, axis=1) takes a row. A function for s.map(f) takes a single value.
Callables in other pandas methods
The same idea appears outside the four methods above. Several pandas methods accept a callable, and they call it with the whole object instead of a piece of it:
import pandas as pd
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
result = (
df.assign(total=lambda d: d["price"] * d["qty"])
.loc[lambda d: d["total"] > 15]
)
print(result)The output is:
price qty total
1 20.0 2 40.0
2 30.0 3 90.0Here assign calls the lambda with the DataFrame as it is at that point in the chain, and loc does the same with the DataFrame returned by assign. The lambda in loc can therefore refer to the total column, which did not exist in the original df. These calls pass the whole object, so they are not element-wise. You can still do element-wise work inside them, but the usual choice is a vectorized expression like the one above.
Other methods that accept callables include pipe, sort_values(key=...), groupby(...).agg(...), rename(columns=...) and where. The sort_values key function receives a whole Series, so you can use vectorized string methods in it:
import pandas as pd
names = pd.Series(["bob", "Alice", "carol"])
print(names.sort_values(key=lambda x: x.str.lower()))The result is Alice, bob, carol. Without the key, sorting is case-sensitive and puts Alice first only because uppercase letters sort before lowercase. The key makes the intent explicit and gives the same order for any mix of cases.
What your function must return
The return value is part of the contract. For map and Series.apply, return one value per element. If your function has no return statement, Python returns None, and the result is a Series full of missing values:
import pandas as pd
s = pd.Series([1, 2, 3])
def forgot_return(x):
x * 2
print(s.map(forgot_return))All three results are None. This is a common mistake with multi-line functions and it raises no error. Always check the first few rows of the result.
For DataFrame.apply, the return type also decides the shape of the result: a scalar per column or row gives a Series, and a Series per column or row gives a DataFrame. A later chapter covers this.
Common errors
These mistakes come up often when people first pass functions to pandas.
- Calling the function instead of passing it.
s.map(str.upper())fails becausestr.upperis called with no argument before pandas sees it. Writes.map(str.upper). - Writing for the wrong unit. A function that does
row["price"]fails withmap, becausemappasses an element, not a row. Check the table above first. - Forgetting a return value. The result is
Nonein every position, as shown above. - Mutating the argument. When the function receives a row or column Series, changing it in place is unreliable. The result may depend on whether pandas gave you a copy. Build and return a new value.
- Using a function that can't handle missing values.
str.upperraises an error onNoneorNaN. A later chapter coversna_actionand other ways to handle this. - Using an old method name.
df.mapraisesAttributeErroron pandas versions before 2.1. Checkpd.__version__.
Where this goes next
The following chapters take each method in turn. They cover map with functions and with dicts, missing values, Series.apply and its extra arguments, and how to choose between map and apply. They then cover DataFrame.apply on rows and columns, the element-wise DataFrame.map, result shapes, vectorized alternatives, groupby with apply, and a closing set of pitfalls. In every one of them the question to ask first is the same: what is the unit, and what should my function return for it?
Exercise
You call df.apply(f, axis=1) on a DataFrame with 5 rows and 3 columns. How many times is f called, and what type of object does each call receive?
Show answer
f is called 5 times, once per row. Each call receives a Series that holds the 3 values of that row, indexed by the column names.
Exercise
A colleague writes prices.map(add_tax(rate=0.2)) and gets an error. Explain the mistake and give two ways to fix it, assuming add_tax(price, rate) is defined as in this chapter.
Show answer
add_tax(rate=0.2) calls the function immediately without the required price argument, so Python raises an error before pandas runs. pandas needs a callable. Fix 1: prices.map(partial(add_tax, rate=0.2)). Fix 2: prices.map(lambda p: add_tax(p, 0.2)).
Exercise
What does this return, and why? pd.Series([1, 2, 3]).map(lambda x: print(x))
Show answer
It prints 1, 2 and 3 on separate lines, then returns a Series of three None values. print returns None, and pandas collects the return values of the function, not what it printed.