Sub topic 12
Inspecting intermediate results without breaking the chain
This chapter assumes you can write a chain with assign, query, and sort_values, and that you know how pipe passes a DataFrame to a function. The sample df is the four-row orders table used earlier.
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],
})The problem with a chain
A chain has no named intermediate variables. If the final result looks wrong, you cannot print the DataFrame between step two and step three. Splitting the chain into separate statements works, but it destroys the structure you built.
The fix is a pass-through function. It receives the DataFrame, reports something about it, and returns the same DataFrame. Because it returns its input unchanged, pipe hands the data to the next step as if the function were not there.
A pass-through function
def log_shape(data, label):
print(label, data.shape)
return data
result = (
df
.pipe(log_shape, "start")
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > 20")
.pipe(log_shape, "after filter")
)This prints two lines:
start (4, 4)
after filter (2, 5)The shape shows the filter dropped two rows and the assign added one column. You can read the chain's effect step by step without changing its result.
Other useful pass-through functions
The same pattern supports more than shapes. Any function that returns data is safe to insert.
Print a few rows with a label:
def peek(data, label, n=3):
print(f"--- {label} ---")
print(data.head(n))
return dataStop the chain when a rule is violated:
def check_positive(data, column):
assert (data[column] > 0).all(), f"{column} has non-positive values"
return data
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe(check_positive, "revenue")
.pipe(peek, "after check")
)The assertion turns an assumption into a check. If it fails, the error names the column and points at the step where the data went wrong.
Debugging workflow
- Run the whole chain and note which result is wrong.
- Insert
.pipe(peek, "label")after the step you suspect. - Move the call earlier or later until the data first looks wrong.
- Fix that step, then delete the debugging calls.
You can also comment out lines from the bottom of the chain. Each line starts with a dot, so removing the last steps leaves a valid chain.
Common mistakes
- Forgetting
return data. The function returnsNone, and the next step fails withAttributeError: 'NoneType' object has no attribute .... If a chain breaks right after apipe, check this first. - Modifying the data inside the helper. A debugging function that changes the DataFrame, for example by sorting it in place, alters the result. Keep these functions read-only.
- Leaving them in. Printing helpers add noise and cost time on large data. Remove them when the chain works, and keep only the assertions you want as permanent guards.
Exercise
A colleague writes def show(data): print(data.head()) and uses df.pipe(show).query("price > 5"). The chain raises an AttributeError. What is wrong, and how do you fix it?
Show answer
show returns None because it has no return statement, so .query is called on None. Add return data at the end of the function. After the fix, pipe passes the original DataFrame to query.