Sub topic 6
Passing extra arguments to your function
This chapter assumes you can write a Python function with positional and keyword parameters, and that you can create a Series or DataFrame and assign a new column. It also assumes you have met Series.map and Series.apply in the earlier chapters. The code uses pandas 2.1 or later, because one example uses DataFrame.map.
Why extra arguments matter
The methods in this tutorial call your function with one thing at a time. Series.apply passes one element, and DataFrame.apply passes one column or one row. Real functions usually need more than that, such as a tax rate, a threshold or a label.
You could hard-code the value inside the function or read it from a global variable. Both make the function hard to reuse and hard to test. It is better to give the function ordinary parameters and let pandas forward the values for you.
The rule is that pandas calls func(item, *args, **kwargs), where item is the element, column or row.
The first parameter of your function always receives the data. Everything else comes from args and the keyword arguments, and the same values are used for every call.
Keyword arguments with Series.apply
Any keyword argument that Series.apply does not recognize is passed on to your function:
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.25))0 12.5
1 25.0
2 37.5
dtype: float64The call prices.apply(add_tax, rate=0.25) runs add_tax(10.0, rate=0.25), then add_tax(20.0, rate=0.25), and so on. You can run the same function with another rate by changing only the call.
Positional arguments with args
Series.apply also has an args parameter. It takes a tuple, and pandas unpacks the tuple after the element:
import pandas as pd
def clip_to(value, low, high):
return max(low, min(value, high))
s = pd.Series([-5, 50, 120])
print(s.apply(clip_to, args=(0, 100)))0 0
1 50
2 100
dtype: int64Here pandas calls clip_to(-5, 0, 100), clip_to(50, 0, 100) and clip_to(120, 0, 100).
You can use args and keyword arguments together. Positional values must come first in the function's parameter list, in the same order as in the tuple:
import pandas as pd
def label(score, threshold, high="pass", low="fail"):
return high if score >= threshold else low
scores = pd.Series([45, 60, 82])
print(scores.apply(label, args=(60,), high="PASS", low="FAIL"))0 FAIL
1 PASS
2 PASS
dtype: objectThe one-element tuple trap
args must be a tuple (or another iterable). A one-element tuple needs a trailing comma, because parentheses alone do not make a tuple:
args=(60,)is a tuple with one value.args=(60)is just the integer60. pandas then tries to unpack an integer and raises aTypeError.args=("abc")is just the string"abc". pandas unpacks it into three one-character arguments, and your function fails with a confusing "too many arguments" error.
Series.map does not forward arguments
Series.map takes a function, a dict or a Series, plus na_action. In pandas 2.x its signature has no place for extra arguments to your function. If you try s.map(add_tax, rate=0.25), pandas raises a TypeError about an unexpected keyword argument.
Wrap the function so that the extra values are already fixed. There are two common ways. The first is functools.partial, which creates a new callable with some arguments filled in:
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])
with_tax = partial(add_tax, rate=0.25)
print(prices.map(with_tax))The second is a lambda:
import pandas as pd
def add_tax(price, rate):
return price * (1 + rate)
prices = pd.Series([10.0, 20.0, 30.0])
print(prices.map(lambda p: add_tax(p, rate=0.25)))Both print the same result as the apply version. Use partial when you want a named, reusable callable. Use a lambda for a one-off call. Either wrapper works with every pandas method in this chapter, so it is also the fallback whenever the argument-forwarding rules below get in your way.
Lambdas created in a loop
A lambda looks up variables when it runs, not when it is created. This matters if you build several lambdas in a loop:
import pandas as pd
s = pd.Series([1, 2, 3])
funcs = [lambda x: x * n for n in (10, 100)]
print(s.map(funcs[0]).tolist())[100, 200, 300]The first lambda should multiply by 10, but by the time it runs, n is 100. Binding the value as a default argument (lambda x, n=n: x * n) or using partial fixes this, because both capture the value immediately.
DataFrame.apply
DataFrame.apply accepts the same args tuple and keyword arguments. Your function still receives a column (with the default axis=0) or a row (with axis=1) as its first argument.
Column-wise, with a keyword argument for each parameter:
import pandas as pd
def scale(col, factor, offset=0):
return col * factor + offset
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
print(df.apply(scale, factor=10, offset=1)) a b
0 11 41
1 21 51
2 31 61Row-wise, extra arguments let one function work with different settings:
import pandas as pd
def total(row, tax):
return row["price"] * row["qty"] * (1 + tax)
df = pd.DataFrame({"price": [10.0, 20.0, 30.0], "qty": [1, 2, 3]})
df["total"] = df.apply(total, axis=1, tax=0.5)
print(df) price qty total
0 10.0 1 15.0
1 20.0 2 60.0
2 30.0 3 135.0Notice that axis=1 is an option of apply itself, while tax=0.5 is forwarded to total.
Name collisions
pandas reads its own parameters first. Names such as func, axis, raw, result_type, args and by_row belong to apply, so a keyword with one of those names never reaches your function. Suppose your function has a parameter called axis or args. Then a call like df.apply(f, axis=2) is interpreted by pandas, not by f.
The fix is to rename the parameter in your function, or to pass the value through a partial or lambda wrapper, which hides the name from pandas.
DataFrame.map and groupby apply
DataFrame.map applies a function to every cell and also forwards keyword arguments:
import pandas as pd
def power(x, exponent):
return x ** exponent
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})
print(df.map(power, exponent=2)) a b
0 1 9
1 4 16Grouped apply forwards extra values as well. Here the arguments come directly after the function, as *args and **kwargs, and there is no args= tuple:
import pandas as pd
def spread(s, scale):
return (s.max() - s.min()) * scale
df = pd.DataFrame({"team": ["x", "x", "y", "y"], "score": [3, 9, 4, 6]})
print(df.groupby("team")["score"].apply(spread, scale=0.5))team
x 3.0
y 1.0
Name: score, dtype: float64Summary of where arguments go
| Method | How to pass extra values |
|---|---|
| `Series.map` | Not supported in pandas 2.x. Wrap the function with `partial` or a lambda. |
| `Series.apply` | `args=(...)` tuple and keyword arguments. |
| `DataFrame.apply` | `args=(...)` tuple and keyword arguments. |
| `DataFrame.map` | Keyword arguments. |
| `groupby(...).apply` | Positional and keyword arguments directly after the function. |
Limits of extra arguments
Extra arguments are constants. Every call receives the same values, so they cannot supply a different value for each element. If each row needs its own second value, that value should be in the data. Put it in another column and use axis=1 or, better, a vectorized expression across the columns.
Extra arguments also do not make a function faster. partial, lambdas and args= all still call Python code once per element. For simple arithmetic, a vectorized form is shorter and usually much faster:
import pandas as pd
prices = pd.Series([10.0, 20.0, 30.0])
rate = 0.25
print(prices * (1 + rate))Reserve the techniques in this chapter for logic that you cannot easily express with built-in operations, such as branching on string contents or calling a library function that handles one value at a time.
Common errors
TypeError: ... got an unexpected keyword argument: you passed a keyword toSeries.map, or the name does not match a parameter of your function. Check the spelling, and use a wrapper formap.TypeError: ... missing 1 required positional argument: you forgot to supply a parameter that has no default value.- A "too many arguments" error after
args=("text"): the parentheses did not create a tuple, so the string was unpacked. Writeargs=("text",). - A keyword that seems to be ignored: it may match one of the
applyparameters listed above.
Exercise
You have a Series s = pd.Series([3, 15, 8]) and a function def cap(value, limit): return min(value, limit). Write one call that caps every value at 10 using Series.apply with a keyword argument. Then write a second call that does the same with Series.map. Why does the second call need extra code?
Show answer
s.apply(cap, limit=10) returns 3, 10, 8. For map, wrap the function: s.map(partial(cap, limit=10)) (after from functools import partial) or s.map(lambda v: cap(v, 10)). Series.map in pandas 2.x has no way to forward extra arguments, so it needs a wrapper that fixes limit first.