Sub topic 9
Putting your own functions in a chain with pipe
This chapter assumes you can write Python functions and lambdas, build and inspect a DataFrame, filter rows, and use groupby with basic aggregation. You should also know that assign adds columns inside a chain. Here you will learn how pipe lets your own functions take part in the same chain.
The problem pipe solves
Built-in methods such as query and sort_values chain naturally because they are methods on the DataFrame. Your own functions are not. Suppose you have a function add_tax(data, rate). Without pipe, you must break the chain or wrap it in a call:
result = add_tax(df, rate=0.2).query("total > 20")This reads inside-out. With more steps, the function calls nest and the order of operations becomes hard to follow. pipe puts the call back into the left-to-right flow.
How pipe works
df.pipe(func, *args, **kwargs) calls func(df, *args, **kwargs) and returns the result. The DataFrame is passed as the first argument. Because the return value is usually a new DataFrame, you can keep chaining.
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 > 20")
)
print(result)pipe hands df to add_tax as data. The keyword rate=0.2 is forwarded unchanged. The function returns a new DataFrame with a total column, and query then filters it.
When the DataFrame is not the first argument
By default pipe passes the DataFrame as the first positional argument. If your function has a different signature, pass a tuple of (callable, keyword). The keyword names the parameter that should receive the DataFrame.
def scale_price(factor, data):
return data.assign(price=data["price"] * factor)
result = df.pipe((scale_price, "data"), factor=2)
print(result)Here data is the second parameter. The tuple tells pipe to supply the DataFrame as data=df, so factor=2 fills the other parameter.
Designing pipe-friendly functions
A function works well in a chain when it follows a few habits:
- It takes the DataFrame as its first parameter.
- It returns a DataFrame, so the next step has something to work on.
- It does not modify its input. Use
assignor other methods that return new objects, rather than writingdata["x"] = ...on the argument. - It takes configuration as extra arguments, such as
rate, instead of reading global variables.
The add_tax function above follows all four. Because it uses assign internally, the original df is untouched.
Pipe versus assign
Use assign when the step creates or replaces columns and can be written as a short expression. Use pipe when the step needs several lines, is reused in other places, or does something assign cannot express, such as renaming columns, dropping rows, or validating the input. Both return a new DataFrame, so they combine freely.
| Need | Reach for |
|---|---|
| One new column from a simple expression | `assign` |
| Multi-line logic or a reusable step | `pipe` |
| Function whose DataFrame parameter is not first | `pipe((func, "name"), ...)` |
Exercise
You have def clip_column(column, data, upper): return data.assign(**{column: data[column].clip(upper=upper)}). Write a chain step that limits the price column of df to a maximum of 15.
Show answer
Because data is not the first parameter, use the tuple form: df.pipe((clip_column, "data"), column="price", upper=15). The tuple tells pipe to pass the DataFrame as data, and the keywords supply column and upper.