Sub topic 13
Pitfalls: inplace, long chains, and when to stop chaining
This chapter assumes you know basic Python, can build and filter a pandas DataFrame, and have used assign, pipe, and groupby in a chain. Chains are easy to write and easy to overuse. Here are the failures you are most likely to hit and a way to decide when to stop.
Pitfall 1: inplace=True breaks the chain
Chaining works because each method returns a new DataFrame. Methods called with inplace=True modify the object and return None. The next call in the chain then runs on None.
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],
})
try:
result = (
df
.sort_values("price", inplace=True)
.reset_index(drop=True)
)
except AttributeError as err:
print(err)The error is 'NoneType' object has no attribute 'reset_index'. It also changed df as a side effect. Leave inplace at its default of False in a chain.
Pitfall 2: lambdas that capture the wrong DataFrame
A lambda in assign should read from its argument. If you write df["price"] instead of d["price"], you read the original DataFrame, not the intermediate one. The two can differ in length after a filter.
bad = (
df
.query("price > 5")
.assign(revenue=df["price"] * df["quantity"])
)
good = (
df
.query("price > 5")
.assign(revenue=lambda d: d["price"] * d["quantity"])
)
print(bad)
print(good)Here bad still gives the right values, because pandas aligns the original columns by index. That makes the mistake easy to miss. It breaks once an earlier step resets the index or changes the rows. Use the lambda argument every time.
Pitfall 3: chains that grow too long
A chain of four steps reads well. A chain of twenty does not. Warning signs:
- You scroll to see the whole chain.
- You cannot name what the chain produces in one phrase.
- A failure gives a traceback that points to the whole statement, not the step that failed.
- One step needs a long comment to explain it.
Break a long chain into named stages. Each stage should be a chain a reader can summarize in a sentence.
def with_revenue(data):
return data.assign(revenue=lambda d: d["price"] * d["quantity"])
cleaned = df.pipe(with_revenue).query("revenue > 20")
summary = (
cleaned
.groupby("region", as_index=False)
.agg(total_revenue=("revenue", "sum"), orders=("order_id", "count"))
.sort_values("total_revenue", ascending=False)
)
print(summary)The intermediate name cleaned gives you a place to inspect the data, and it documents what the first half does.
Pitfall 4: side effects inside steps
A function passed to pipe should return a new DataFrame and leave its input alone. A function that edits its argument also edits the caller's variable.
def bad_step(data):
data["revenue"] = data["price"] * data["quantity"]
return data
def good_step(data):
return data.assign(revenue=data["price"] * data["quantity"])After df.pipe(bad_step), df has a revenue column. After df.pipe(good_step), it does not.
When a plain statement is clearer
Use a separate statement when:
- The step is a one-off mutation, such as
df.loc[mask, "x"] = 0, which does not chain naturally. - You need the same intermediate result in two later computations.
- The logic has branches or loops.
- You are debugging and want to inspect each stage.
A decision rule: chain a linear sequence of transformations where each step feeds only the next one. Otherwise, use named variables.
Exercise
This code raises an error. Why, and how do you fix it? result = df.assign(revenue=df["price"] * df["quantity"]).dropduplicates(inplace=True).sortvalues("revenue")
Show answer
dropduplicates(inplace=True) modifies the DataFrame and returns None, so sortvalues is called on None and raises AttributeError. Remove inplace=True so the method returns a new DataFrame: df.assign(revenue=lambda d: d["price"] * d["quantity"]).dropduplicates().sortvalues("revenue"). Using a lambda in assign is also safer than reading df directly.
Exercise
Name two signs that a chain should be split, and one case where a plain statement is better than a chain.
Show answer
Signs: the chain no longer fits on one screen, or you cannot describe its result in one sentence (a step needing a long comment also counts). A plain statement is better for a one-off mutation such as df.loc[mask, "x"] = 0, or when two later computations need the same intermediate result.