Sub topic 11
Designing reusable pipe-friendly functions
This chapter assumes you can write a basic Python function, use assign and pipe in a chain, and run groupby aggregations. It covers how to write functions that work well inside pipe and can be reused across projects.
The contract of a pipe-friendly function
pipe calls func(df, *args, **kwargs) and uses the return value as the next object in the chain. A function that fits this contract follows four rules:
| Rule | Reason |
|---|---|
| Take the DataFrame as the first parameter | `pipe` passes it there by default |
| Return a DataFrame | The next step needs something to work on |
| Do not modify the input | The caller's variable stays unchanged |
| Take configuration as extra arguments | Column names and thresholds are not hard-coded |
A small function library
Each function below does one job and takes the column name as an argument.
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_revenue(data):
return data.assign(revenue=data["price"] * data["quantity"])
def keep_above(data, column, minimum):
return data.loc[data[column] > minimum]
def top_n(data, column, n=3):
return data.nlargest(n, column)
result = (
df
.pipe(add_revenue)
.pipe(keep_above, "revenue", 20)
.pipe(top_n, "revenue", n=2)
)
print(result)Inside add_revenue, data is already the current frame. You don't need a lambda there, because the function receives the intermediate state directly.
Reading the chain, each step names what it does. You can also test each function alone by calling add_revenue(df).
Do not mutate the input
A common mistake is to assign into the argument:
def add_revenue_bad(data):
data["revenue"] = data["price"] * data["quantity"]
return dataThis changes the caller's df, even though it looks like part of a chain. The same chain run twice gives surprising results, and pandas may raise a SettingWithCopyWarning if data came from a filter. Use assign, or call data = data.copy() first when you must write with item assignment.
Configuring functions with factories
Sometimes the extra arguments make a chain noisy, or you want to build a step once and reuse it. A factory is a function that returns a pipe-friendly function:
def with_ratio(numerator, denominator, name):
def step(data):
return data.assign(**{name: data[numerator] / data[denominator]})
return step
result = (
df
.pipe(add_revenue)
.pipe(with_ratio("revenue", "quantity", "unit_price"))
)
print(result)with_ratio(...) runs immediately and returns step. pipe then calls step(df). The **{name: ...} form lets the caller choose the new column name, as in the earlier lesson on names that are not valid identifiers.
Use a factory when you apply the same configured step in several places. For a single use, extra arguments to pipe are simpler.
Design guidelines
- Keep each function small. If its name needs "and", split it.
- Put the DataFrame first. If you must use a third-party function with the frame in another position, use the
(callable, keyword)form instead of changing the signature. - Give column names as arguments with sensible defaults only when one default is almost always right.
- Do not rely on columns the caller may not have. Fail early with a clear message:
def add_revenue(data):
missing = {"price", "quantity"} - set(data.columns)
if missing:
raise KeyError(f"add_revenue needs columns: {sorted(missing)}")
return data.assign(revenue=data["price"] * data["quantity"])- Avoid printing or writing files inside transformation functions. Logging belongs in a separate pass-through function, covered in the next chapter.
Exercise
Write a pipe-friendly function drop_small(data, column, minimum) that returns only rows where column is at least minimum, without modifying data. Then use it in a chain on df after add_revenue to keep orders with revenue of at least 30.
Show answer
def dropsmall(data, column, minimum):
return data.loc[data[column] >= minimum]
result = df.pipe(addrevenue).pipe(drop_small, "revenue", 30)
The function takes the DataFrame first, returns a new filtered DataFrame, and never assigns into data. Revenue values are 20, 20, 45 and 50, so the result holds orders 3 and 4.