Sub topic 10
Extra arguments and the (callable, keyword) form
This chapter assumes you can write a basic chain, use assign with lambdas, and write a plain Python function with positional and keyword parameters. It also assumes you have already used pipe to run a one-argument function in a chain. Here you will see how pipe passes extra arguments, what happens when the DataFrame is not the function's first parameter, and which mistakes cause most of the errors.
How pipe forwards arguments
DataFrame.pipe(func, *args, **kwargs) calls func(df, *args, **kwargs), where df is the DataFrame on the left of .pipe. The DataFrame always goes first. Any extra arguments you give to pipe follow it unchanged.
Here is a function with one extra parameter:
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 15.0, 5.0],
"quantity": [2, 1, 3, 10],
})
def add_tax(data, rate):
return data.assign(total=data["price"] * data["quantity"] * (1 + rate))
result = (
df
.pipe(add_tax, rate=0.2)
.query("total > 30")
)
print(result)The call .pipe(add_tax, rate=0.2) becomes add_tax(df, rate=0.2). Only orders 3 and 4 survive the filter, because their totals are about 54 and 60.
You can also pass extras by position. .pipe(add_tax, 0.2) becomes add_tax(df, 0.2). Keywords are usually better here, because the chain then shows what 0.2 means.
Defaults, keyword-only parameters, and *args all work as they do in a normal call. Suppose the function looks like this:
def filter_region(data, region, min_revenue=0):
revenue = data["price"] * data["quantity"]
return data[(data["region"] == region) & (revenue >= min_revenue)]
east_big = df.pipe(filter_region, "east", min_revenue=25)
print(east_big)Python sees filter_region(df, "east", min_revenue=25). Only order 3 matches, with a revenue of 45.
When the DataFrame is not the first parameter
Some functions put the DataFrame later in the signature. Functions from other libraries often do, and so do functions written for another purpose. Look at this one:
def scale_price(factor, data):
return data.assign(price=data["price"] * factor)The call df.pipe(scale_price, factor=2) fails. pipe calls scale_price(df, factor=2), so df binds to factor by position, and then factor=2 binds it a second time. Python raises:
TypeError: scale_price() got multiple values for argument 'factor'The fix is the (callable, keyword) form. Replace the function with a two-item tuple. The first item is the callable, and the second is a string naming the parameter that should receive the DataFrame:
result = df.pipe((scale_price, "data"), factor=2)
print(result)Now pipe calls scale_price(factor=2, data=df). The DataFrame is passed by keyword instead of by position, so its place in the signature no longer matters.
What pipe does with the tuple
The logic inside pipe is short. If the first argument is a tuple, it unpacks it into a callable and a target name. It then adds target=df to the keyword arguments and calls the callable with your *args and the updated **kwargs. If the first argument is not a tuple, it calls func(df, *args, **kwargs).
Positional extras still work with the tuple form. Because the DataFrame arrives by keyword, any positional arguments you supply fill the other parameters in order:
result = df.pipe((scale_price, "data"), 2)This calls scale_price(2, data=df), which is valid.
A function with several extra parameters
Consider a function where the DataFrame sits between two other parameters:
def keep_top(n, data, column):
return data.nlargest(n, column)
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe((keep_top, "data"), 2, column="revenue")
.reset_index(drop=True)
)
print(result)pipe calls keep_top(2, column="revenue", data=<intermediate frame>). The intermediate frame is the one that already has the revenue column, so nlargest can see it. The two rows with the highest revenue are orders 4 (50.0) and 3 (45.0).
Choosing between the forms
| Situation | Form | Call made |
|---|---|---|
| DataFrame is the first parameter | `.pipe(f, rate=0.2)` | `f(df, rate=0.2)` |
| DataFrame is not first | `.pipe((f, "data"), factor=2)` | `f(factor=2, data=df)` |
| You want to fix some arguments in advance | `.pipe(partial(f, 2))` | `f(2, df)` |
| You want to rename or reorder arguments | `.pipe(lambda d: f(2, d))` | `f(2, df)` |
The tuple form needs the parameter to be accepted by keyword. A parameter declared positional-only, with / in the signature, cannot receive the DataFrame this way. Many built-in and C-implemented functions have positional-only parameters. For those, use a lambda or functools.partial.
partial works when the DataFrame belongs in the first free position. It is a good fit for scale_price:
from functools import partial
result = df.pipe(partial(scale_price, 2))partial(scale_price, 2) creates a callable that fixes factor=2. pipe then calls it with df, which becomes scale_price(2, df). This only works when the DataFrame comes after the fixed arguments. The tuple form is more general because it never depends on position.
Arguments are evaluated when the chain is built
The extra arguments are ordinary Python expressions. Python evaluates them when it builds the call, not when the previous step finishes. The values cannot refer to the intermediate DataFrame:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe(lambda d, cutoff: d[d["revenue"] > cutoff], cutoff=df["price"].mean())
)Here df["price"].mean() is the mean of the original df, which is 12.5. If an earlier step had filtered rows, the cutoff would still come from the unfiltered data. This is a common source of quiet bugs.
If you need a value derived from the current state, compute it inside the function that pipe calls:
def above_mean_revenue(data):
revenue = data["price"] * data["quantity"]
return data[revenue > revenue.mean()]
result = df.pipe(above_mean_revenue)The function receives the current frame, so the mean always matches the rows it is filtering.
Common errors
These are the mistakes behind most pipe failures with extra arguments.
- Calling the function instead of passing it.
df.pipe(add_tax(rate=0.2))callsadd_taxright away, withoutdata, and raises aTypeErrorabout a missing argument. Passadd_taxandrate=0.2separately. - Reversing the tuple.
(“data”, scale_price)fails, because the callable comes first and the name second. - Naming the wrong parameter. If the function has no parameter called
"data", the call fails with an unexpected keyword argument error. - Supplying the target twice. Passing
data=...inkwargswhile also using(f, "data")raisesValueError: data is both the data argument and a keyword argument. - Forgetting to return a DataFrame. A function that modifies its input and returns
Noneends the chain. The next method call then fails withAttributeError: 'NoneType' object has no attribute ....
If you want a step with preset arguments that reads cleanly, you can also write a factory. A factory is a function that returns the step:
def with_tax(rate):
def step(data):
return data.assign(total=data["price"] * data["quantity"] * (1 + rate))
return step
result = df.pipe(with_tax(0.2)).query("total > 30")The factory runs once, at chain-build time, and pipe then calls the returned step with the DataFrame. This hides the argument handling, at the cost of an extra layer of code.
Exercises
Exercise
Given def clip_column(limit, frame, column): return frame.assign(**{column: frame[column].clip(upper=limit)}), write a chain that pipes df through it so that price is capped at 12. Use the (callable, keyword) form.
Show answer
df.pipe((clip_column, "frame"), 12, column="price"). The call becomes clip_column(12, column="price", frame=df). The string must be "frame", because that is the name of the parameter that receives the DataFrame.
Exercise
Why does df.pipe(scale_price, factor=2) fail for def scale_price(factor, data), and what error do you get?
Show answer
pipe calls scale_price(df, factor=2). The DataFrame fills factor by position, and the keyword then supplies factor a second time, so Python raises TypeError: scale_price() got multiple values for argument 'factor'. Use df.pipe((scale_price, "data"), factor=2) instead.
Exercise
A chain filters df down to the east region and then pipes it through a function with threshold=df["price"].mean(). Why is the threshold possibly wrong, and how do you fix it?
Show answer
The expression df["price"].mean() is evaluated when the call is built, so it uses the original df, not the filtered frame. Compute the mean inside the function from its data argument, so it always reflects the frame that pipe passes in.