Sub topic 3
Putting Your Own Functions in a Chain with `pipe`
This chapter assumes basic Python functions and lambda expressions, DataFrame selection and filtering, and groupby with simple aggregation.
Put Functions into a Chain
pipe passes the current DataFrame to a function and returns that function's result. This lets custom transformations fit beside pandas methods.
import pandas as pd
df = pd.DataFrame({
"price": [10.0, 20.0, 15.0],
"quantity": [2, 1, 3],
})
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)The DataFrame becomes the first argument to add_tax. The keyword rate=0.2 is passed as an extra argument.
Passing Arguments and Naming the DataFrame Parameter
Usually, the DataFrame is the function's first parameter. If it is not, use a (callable, keyword) tuple:
def scale_price(factor, data):
return data.assign(price=data["price"] * factor)
result = df.pipe((scale_price, "data"), factor=2)Here, pipe sends the DataFrame to the parameter named data.
A reusable function should do one clear transformation. Give important settings explicit parameters, and return the transformed object instead of printing or storing hidden state.
Inspect Intermediate Results
A pass-through function can inspect a chain without ending it:
def log_shape(data, label):
print(label, data.shape)
return data
result = (
df
.pipe(log_shape, "start")
.pipe(add_tax, rate=0.2)
.pipe(log_shape, "after tax")
.query("total > 20")
)Because log_shape returns data, the next method receives the same DataFrame.
Know When to Stop Chaining
Avoid inplace=True inside a chain. In-place methods commonly return None, so the next method cannot run. Prefer methods that return new DataFrames.
Long chains can also hide errors. Break a chain into named steps when you need to reuse an intermediate result, handle a branch, add complex conditional logic, or explain a difficult transformation. Chaining is useful when each step reads clearly from top to bottom.
Exercise
What must a function return for it to continue a pandas chain?
Show answer
It must return the next object in the transformation, normally a DataFrame.