Sub topic 11
Designing reusable pipe-friendly functions
This chapter assumes you can write a method chain with assign, you know how DataFrame.pipe calls a function with the DataFrame as its first argument, and you are comfortable with Python functions, default arguments, and functools.partial. Earlier chapters showed that pipe lets you place your own functions in a chain. This chapter covers how to write functions that behave well there.
What "pipe-friendly" means
df.pipe(func, *args, **kwargs) calls func(df, *args, **kwargs) and returns whatever func returns. Nothing forces func to behave well, so the discipline comes from you. A pipe-friendly function follows these rules:
- It takes the DataFrame as its first parameter, so
pipeneeds no tuple form. - It returns a DataFrame, so the next method in the chain still works.
- It does not modify its input or any other object.
- It takes configuration through parameters instead of reading globals.
- It does one describable job, and its name says what the job is.
Each rule protects a property that makes chains readable: you can read the steps top to bottom, and you can rerun any step without side effects.
Here is the smallest useful example.
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: pd.DataFrame) -> pd.DataFrame:
return data.assign(revenue=data["price"] * data["quantity"])
result = df.pipe(add_revenue).query("revenue > 20")
print(result)Inside add_revenue, data is the DataFrame the chain has produced so far. You can use it directly, with no lambda, because the function is called at that point in the chain and receives the current state as an argument. This is the same idea as the lambda in assign, with a named function in its place.
Never mutate the input
The most common defect in pipe functions is changing the caller's DataFrame. It looks harmless because the function also returns the frame.
def add_revenue_bad(data):
data["revenue"] = data["price"] * data["quantity"]
return data
original = pd.DataFrame({"price": [10.0, 20.0], "quantity": [2, 1]})
result = original.pipe(add_revenue_bad)
print("revenue" in original.columns)The output is True. The function added a column to original. A chain that starts from a variable you still use later now changes that variable, and rerunning a notebook cell gives different results from running it once.
You have two safe ways to write the function:
- Use
assign, which returns a new DataFrame. This is usually the best choice. - Call
data.copy()first if you must use item assignment,drop, or another step that is awkward without a mutable object.
def add_revenue_copy(data):
out = data.copy()
out["revenue"] = out["price"] * out["quantity"]
return outMake configuration explicit
A pipe function should name its inputs. Hard-coded column names and global constants make a function work in one notebook and nowhere else.
def add_ratio(data, numerator, denominator, name):
return data.assign(**{name: data[numerator] / data[denominator]})
def keep_regions(data, regions):
return data[data["region"].isin(regions)]
result = (
df
.pipe(add_revenue)
.pipe(add_ratio, "revenue", "quantity", name="unit_price")
.pipe(keep_regions, ["east"])
)
print(result)add_ratio uses assign(**{name: ...}) because the new column's name arrives in a variable. This is the same dictionary-unpacking form you used for names that are not valid identifiers. In the call, "revenue" and "quantity" are passed by position and name as a keyword. Mixing the two is fine, but keywords make long calls easier to read.
Choose defaults that reflect the common case, and put them after the required parameters:
def add_ratio(data, numerator, denominator, name=None):
name = name or f"{numerator}_per_{denominator}"
return data.assign(**{name: data[numerator] / data[denominator]})Fixing arguments with partial
When you use the same configuration in many places, bind it once with functools.partial. The result is a callable that takes only the DataFrame.
from functools import partial
def add_tax(data, rate):
return data.assign(total=data["price"] * data["quantity"] * (1 + rate))
add_standard_tax = partial(add_tax, rate=0.2)
result = df.pipe(add_standard_tax).query("total > 20")
print(result)Bind with a keyword (rate=0.2), not by position. A positional binding would fill the first parameter, which is data, and the function would get two values for the same parameter.
The other way to reuse a configuration is a factory function that returns a function. Use it when the configuration needs computation or when you want a descriptive name:
def tax_step(rate):
def step(data):
return data.assign(total=data["price"] * data["quantity"] * (1 + rate))
return step
result = df.pipe(tax_step(0.2))Functions where the DataFrame is not first
Sometimes you inherit a function whose DataFrame parameter comes later. Do not rewrite it. Use the (callable, keyword) form to name the parameter that receives the frame.
def scale_price(factor, data):
return data.assign(price=data["price"] * factor)
result = df.pipe((scale_price, "data"), factor=2)For functions you write yourself, put the DataFrame first. The tuple form is a workaround for code you do not control.
Composing steps into bigger functions
A chain of ten steps is hard to read, but a chain of four named stages is easy. Group related steps into a function that itself takes and returns a DataFrame.
def clean_orders(data):
return (
data
.rename(columns=str.lower)
.drop_duplicates(subset="order_id")
.query("quantity > 0")
)
def add_metrics(data):
return data.assign(
revenue=lambda d: d["price"] * d["quantity"],
share=lambda d: d["revenue"] / d["revenue"].sum(),
)
summary = (
df
.pipe(clean_orders)
.pipe(add_metrics)
.groupby("region", as_index=False)
.agg(total_revenue=("revenue", "sum"), orders=("order_id", "count"))
.sort_values("total_revenue", ascending=False)
)
print(summary)The top-level chain now reads like an outline. Each stage can be tested on its own, which is the main practical benefit of this style.
Testing a pipe function
Because a pipe function depends only on its arguments, a test needs a small DataFrame and a comparison. pandas.testing.assert_frame_equal reports differences in values, dtypes, and index.
from pandas.testing import assert_frame_equal
def test_add_revenue():
given = pd.DataFrame({"price": [2.0, 3.0], "quantity": [4, 5]})
expected = given.assign(revenue=[8.0, 15.0])
assert_frame_equal(add_revenue(given), expected)
def test_add_revenue_does_not_mutate():
given = pd.DataFrame({"price": [2.0], "quantity": [4]})
snapshot = given.copy()
add_revenue(given)
assert_frame_equal(given, snapshot)
test_add_revenue()
test_add_revenue_does_not_mutate()
print("ok")The second test checks the no-mutation rule directly. Add one like it for every function that touches the frame in a way you doubt.
Pass-through and validation functions
Some functions exist only for their side effects, such as logging, checking, or saving. They must return their input unchanged so the chain continues.
def require_columns(data, columns):
missing = set(columns) - set(data.columns)
if missing:
raise KeyError(f"missing columns: {sorted(missing)}")
return data
result = (
df
.pipe(require_columns, ["price", "quantity"])
.pipe(add_revenue)
)Putting a check at the top of a chain gives a clear error message at the boundary, before a later step fails with a vague KeyError. The next chapter uses the same pattern for inspecting intermediate results.
Ending a chain with a non-DataFrame
pipe returns whatever your function returns, so a function can end a chain by returning a number, a Series, or a string.
def total_revenue(data):
return data["revenue"].sum()
total = df.pipe(add_revenue).pipe(total_revenue)
print(total)This is fine as the last step. Anything after it receives a scalar, not a DataFrame, and DataFrame methods will fail with an AttributeError.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Mutating the input with `data[col] = ...` | The original variable gains columns | Use `assign` or work on `data.copy()` |
| Forgetting `return` | Next step fails with `'NoneType' object has no attribute ...` | End every step with an explicit `return` |
| Hard-coded column names | Function works for one dataset only | Pass column names as parameters |
| Reading a global such as `TAX_RATE` | Results change when the global changes | Pass the value as an argument or bind it with `partial` |
| Binding `partial(func, 0.2)` by position | `TypeError: got multiple values for argument` | Bind with a keyword |
| Returning a filtered view that you later assign into | `SettingWithCopyWarning` | Return `data.loc[mask].copy()` if a later step assigns into the result |
| One function that does five things | Hard to name, test, or reuse | Split it and name each part |
When a function is not worth it
A function earns its place if you reuse it, test it, or it gives a confusing step a clear name. For a one-off column calculation, assign with a lambda is shorter and keeps the logic where it is used. A common guideline is to move a step into a function when it needs more than a line or two, when two chains need it, or when you want to unit test it.
Exercise
A colleague writes this function and uses it as df.pipe(flag_large, threshold=50). It runs, but df has an extra large column afterwards. Rewrite the function so it is pipe-friendly, and explain what was wrong.
def flag_large(data, threshold):
data["large"] = data["price"] * data["quantity"] > threshold
return data
Show answer
The function assigns into the DataFrame it receives, so it mutates the caller's object. The fix is to return a new frame with assign:
def flag_large(data, threshold):
return data.assign(large=data["price"] * data["quantity"] > threshold)
An alternative is to start with out = data.copy(), assign into out, and return out. Both leave df unchanged.
Exercise
You have def convert(rate, data) that multiplies the price column by rate. Write the pipe call that applies a rate of 1.1 to df without changing the function. Then say how you would bind the rate once so you can reuse it.
Show answer
Use the tuple form: df.pipe((convert, "data"), rate=1.1). To bind the rate once, use convert_110 = partial(convert, rate=1.1), then call df.pipe(convert_110). The partial call binds rate by keyword, so data remains the first positional argument that pipe supplies.