Sub topic 9
Putting your own functions in a chain with pipe
This chapter assumes you know basic Python functions and lambdas, how to build and inspect a DataFrame, and how groupby and agg work. It also assumes you have seen a short chain of methods like .query(...).sort_values(...). Here you will learn what pipe does, how to write functions that fit into a chain, and which mistakes break one.
The problem pipe solves
A chain reads well as long as every step is a DataFrame method. Sooner or later you need a step that no method provides. It might be a function from your own module, a cleaning routine shared by several scripts, or a function from another library that takes a DataFrame.
Without pipe, you have two bad options. You can break the chain into intermediate variables, or you can wrap the chain in a function call, so the code reads from the inside out:
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"])
# Inside-out: you must start reading at the innermost call.
nested = add_revenue(df).query("revenue > 20")
# Top-down: pipe hands the DataFrame to your function.
piped = df.pipe(add_revenue).query("revenue > 20")
print(piped)
print(nested.equals(piped))The output is:
order_id region price quantity revenue
2 3 east 15.0 3 45.0
3 4 west 5.0 10 50.0
TrueThe two versions give the same result. The second reads in the order the work happens.
What pipe does
df.pipe(func) calls func(df) and returns whatever func returns. That is the whole mechanism. pipe adds no copying, no validation, and no special handling of the result.
df.pipe(add_revenue) # same as add_revenue(df)Because pipe returns the function's result unchanged, the next link in the chain operates on that result. If your function returns a DataFrame, you can keep calling DataFrame methods. If it returns something else, the chain continues on that other object.
flowchart LRUse the next block as the chapter's diagram instead of the empty one above.
Writing a function that fits
A function works well in a chain if it follows three rules.
- It takes the DataFrame as its first parameter.
- It returns a DataFrame, or the object the next step expects.
- It does not change the DataFrame it receives.
The add_revenue function above follows all three. It builds its result with assign, which returns a new DataFrame, so the caller's df is untouched.
Here is a function that changes the shape of the data, used in a longer chain:
def summarize_by_region(data):
return data.groupby("region", as_index=False).agg(
total_revenue=("revenue", "sum"),
orders=("order_id", "count"),
)
summary = (
df
.pipe(add_revenue)
.pipe(summarize_by_region)
.sort_values("total_revenue", ascending=False)
.reset_index(drop=True)
)
print(summary)The output is:
region total_revenue orders
0 west 70.0 2
1 east 65.0 2Each pipe step has a name that says what it does, so the chain reads like an outline. You can also test add_revenue and summarize_by_region on their own with small DataFrames, which is hard to do with a long anonymous chain.
If you need to pass extra arguments to the function, pipe forwards them: df.pipe(func, 0.2) calls func(df, 0.2). The next chapter covers that in detail, including the form for functions where the DataFrame is not the first parameter.
Lambdas, named functions, and assign
You can pass a lambda to pipe:
big_orders = df.pipe(lambda d: d[d["quantity"] > 2])This works, but it hides the intent. For anything beyond a one-line expression, a named function is easier to read, test, and reuse. A lambda is also awkward in tracebacks because it has no name.
pipe and assign both put custom logic in a chain, but they do different jobs.
| Tool | Receives | Returns | Use it when |
|---|---|---|---|
| `assign(col=lambda d: ...)` | The current DataFrame, once per new column | One column's values | You are creating or replacing a column |
| `pipe(func)` | The current DataFrame | Anything, usually a whole DataFrame | The step touches several columns, rows, or the shape of the data |
| A DataFrame method | The DataFrame it is called on | A DataFrame | A built-in method already does the job |
A good rule is to choose the smallest tool that fits. A single derived column belongs in assign. A multi-step cleanup or a reshaping routine belongs in a function used with pipe.
What pipe can be called on
pipe is not limited to DataFrames. Series and GroupBy objects have it too, and it behaves the same way: it calls your function with the object and returns the result. A function written for one type of object works only if the object in the chain is that type. If you pipe a DataFrame into a function that expects a Series, you get an error from inside your function, not from pipe.
Common errors
The function returns None
The most frequent mistake is a function that modifies its input and forgets to return it:
def add_revenue_broken(data):
data["revenue"] = data["price"] * data["quantity"]
# no return statement
result = df.pipe(add_revenue_broken).query("revenue > 20")Python returns None from a function with no return. The query call then fails with AttributeError: 'NoneType' object has no attribute 'query'. The error appears on the line after the real mistake, so the message can be confusing. When you see NoneType in a chain, check the function in the step before the failing one.
This function has a second problem. It writes a revenue column into the caller's df. A step in a chain should never change its input, because other code that holds the same DataFrame will see the change. Use assign, or call data.copy() first if you need item assignment.
def add_revenue_safe(data):
out = data.copy()
out["revenue"] = out["price"] * out["quantity"]
return outCalling the function instead of passing it
pipe expects the function itself. Writing df.pipe(add_revenue(df)) calls the function first and then passes its result (a DataFrame) to pipe, which fails because a DataFrame is not callable. Write df.pipe(add_revenue) with no parentheses after the name.
Returning a different type by accident
A function that ends with return data["revenue"].sum() returns a number. That is fine as the last step of a chain, and it is a useful way to end one. If a later step expects a DataFrame, it fails with an AttributeError about float or int. Decide for each function what type it returns and keep to it.
total = df.pipe(add_revenue).pipe(lambda d: d["revenue"].sum())
print(total)This prints 135.0.
Reusing functions across projects
Because a pipe-friendly function takes a DataFrame and returns a DataFrame, you can keep such functions in a module and import them where needed. A few habits keep them reusable:
- Give each function one job and a verb name, such as
add_revenue,drop_test_orders, orstandardize_columns. - Do not hard-code a DataFrame variable name. Use the parameter, never the global
df. - State required columns in a docstring, or check for them and raise a clear error.
- Return a new object. Never rely on side effects on the input.
def require_columns(data, columns):
missing = [c for c in columns if c not in data.columns]
if missing:
raise KeyError(f"missing columns: {missing}")
return data
checked = df.pipe(require_columns, ["price", "quantity"]).pipe(add_revenue)require_columns returns its input unchanged, so it passes through. Raising an error at the start of a chain gives you a clearer message than a KeyError several steps later.
Exercises
Exercise
This chain fails with "AttributeError: 'NoneType' object has no attribute 'sortvalues'". The function is `def addunitprice(data): data["unitprice"] = data["price"] / data["quantity"], used as df.pipe(addunitprice).sortvalues("unitprice")`. Why does it fail, and how do you fix the function so it also leaves the original df untouched?
Show answer
The function has no return statement, so it returns None, and pipe passes that None to the next step. Fix it by building a new DataFrame and returning it: def add_unit_price(data): return data.assign(unit_price=data["price"] / data["quantity"]). Because assign returns a new DataFrame, the original df does not gain a unit_price column.
Exercise
Write a pipe-friendly function top_region(data) that takes a DataFrame with region and revenue columns and returns the name of the region with the highest total revenue. Then say what type the chain df.pipe(add_revenue).pipe(top_region) returns, and whether you can add .query(...) after it.
Show answer
One solution is def top_region(data): return data.groupby("region")["revenue"].sum().idxmax(). For the sample data it returns the string "west" (total 70.0 against 65.0 for east). The chain returns a plain string, not a DataFrame, so it can only be the last step. Adding .query(...) would raise an AttributeError, because a string has no query method.