Sub topic 6
Passing extra arguments to your function
This chapter assumes you can write Python functions and lambdas, build a pandas Series and DataFrame, and assign new columns. You have already used Series.apply with a one-argument function. Here you will learn how to give that function extra parameters so you can reuse it.
Why extra arguments matter
apply calls your function once for each element and passes the element as the first argument. If the function needs more information, such as a tax rate or a threshold, you have three choices:
- Hard-code the value inside the function. This is simple but makes the function hard to reuse.
- Wrap the call in a lambda that fills in the value.
- Give the values to
applyand let it forward them.
The third choice is usually the cleanest.
Forwarding keyword arguments
Series.apply accepts extra keyword arguments and passes them to your function on every call.
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
print(prices.apply(add_tax, rate=0.2))The element goes into price, and rate=0.2 is sent along each time. The output is 12.0, 24.0 and 36.0. The same function can now serve a different rate without any edits:
print(prices.apply(add_tax, rate=0.05))Positional arguments with args
You can also pass extra positional arguments as a tuple through the args parameter. Each element is still passed first, followed by the values in the tuple.
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
print(prices.apply(add_tax, args=(0.2,)))Note the trailing comma in (0.2,). Without it, Python sees a plain number in parentheses, not a tuple. Keyword arguments are easier to read, so prefer them when the parameter has a clear name.
Lambdas as an alternative
A lambda can capture a value from the surrounding code:
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
rate = 0.2
print(prices.apply(lambda p: add_tax(p, rate)))This gives the same result. It works with map as well, which matters because of the next section.
What map does not forward
Series.map takes a function, a dict, or a Series, plus na_action. It does not forward extra arguments to your function. This call fails:
# TypeError: map() got an unexpected keyword argument 'rate'
prices.map(add_tax, rate=0.2)If you want to use map with a parameterized function, wrap it in a lambda as shown above, or use functools.partial:
import pandas as pd
from functools import partial
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
print(prices.map(partial(add_tax, rate=0.2)))partial creates a new function with rate already set, so map sees a one-argument function.
DataFrame.apply and extra arguments
DataFrame.apply forwards extra arguments in the same way. With the default axis=0, each column is passed as the first argument.
import pandas as pd
def scale(col, factor):
return col * factor
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(scale, factor=10))With axis=1, each row is passed instead. The extra arguments are forwarded in both cases.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: ... missing 1 required positional argument` | You forgot to pass the extra argument. | Add `rate=...` or `args=(...)`. |
| `TypeError: ... unexpected keyword argument` on `map` | `Series.map` does not forward keyword arguments. | Use a lambda or `functools.partial`. |
| `args` seems to be ignored or raises an error | You wrote `args=(0.2)` without the comma. | Write `args=(0.2,)`. |
| Argument lands in the wrong parameter | The element always goes first. | Reorder the parameters or use a lambda. |
Exercise
Write a function clip_high(value, limit) that returns limit if value is greater than limit, otherwise value. Apply it to pd.Series([5, 15, 25]) with a limit of 20, first with apply and then with map. What does each version look like, and what result do you get?
Show answer
Define def clip_high(value, limit): return limit if value > limit else value. With apply: s.apply(clip_high, limit=20). With map, which cannot forward keyword arguments: s.map(lambda v: clip_high(v, 20)) or s.map(partial(clip_high, limit=20)). Both produce 5, 15, 20.
Exercise
Why does s.apply(add_tax, args=(0.2)) fail or behave unexpectedly, and how do you fix it?
Show answer
(0.2) is just the number 0.2, not a tuple, so pandas cannot unpack it as a sequence of arguments. Add a trailing comma to make a one-element tuple: args=(0.2,). Alternatively use the keyword form rate=0.2.