Sub topic 13
Pitfalls: inplace, long chains, and when to stop chaining
This chapter assumes you can write a chain with assign, query, groupby/agg and pipe, and that you know why pandas methods return new DataFrames. It covers the mistakes that break chains or make them misleading, and how to decide when a chain has stopped helping.
All examples use this DataFrame.
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],
})Pitfall 1: inplace=True returns None
Many pandas methods accept inplace=True. The method then changes the existing DataFrame and returns None. A chain passes each step's return value to the next method, so the next call lands on None.
work = df.copy()
try:
work.rename(columns={"price": "unit_price"}, inplace=True).query("quantity > 1")
except AttributeError as err:
print(err)The output is 'NoneType' object has no attribute 'query'. The failing line is the one that follows the inplace call, so the message points away from the real cause.
Remove inplace and let each step return a new DataFrame.
work = (
df
.rename(columns={"price": "unit_price"})
.query("quantity > 1")
)
print(work)Two further points support leaving inplace out of chains entirely.
- It usually does not save memory or time. For most methods pandas builds a new object internally and swaps it into the original.
- It makes code harder to reason about, because the same variable name refers to different data before and after the call.
You can spot other None returns the same way. df.info(), list.sort() and a print call inside a pipe function all return None. If a chain fails with a NoneType error, find the step that returns nothing.
Pitfall 2: referring to the original DataFrame instead of the current one
Inside a chain, the name df still refers to the DataFrame you started with. The intermediate result exists only as the argument passed along the chain. If you write df["price"] in a later step, you get the original values, not the ones earlier steps produced.
stale = (
df
.assign(price=lambda d: d["price"] * 2)
.assign(revenue=df["price"] * df["quantity"])
)
current = (
df
.assign(price=lambda d: d["price"] * 2)
.assign(revenue=lambda d: d["price"] * d["quantity"])
)
print(stale["revenue"].tolist()) # [20.0, 20.0, 45.0, 50.0]
print(current["revenue"].tolist()) # [40.0, 40.0, 90.0, 100.0]The first version runs without error and gives the wrong numbers. This is the strongest reason to use the lambda form of assign: the lambda receives the intermediate DataFrame.
The problem gets worse after filtering. df["price"] is a Series with the full original index. When assigned into a filtered DataFrame, pandas aligns on the index, so you silently mix in values from the unfiltered data.
The rule is that inside a chain, refer to the intermediate state through the lambda or pipe argument, and never through the starting variable.
Pitfall 3: mutating the input inside a pipe function
pipe passes the very DataFrame it received, not a copy. If your function assigns to it with data["new"] = ..., you modify the caller's object and still return it. The chain looks functional, but the original changes.
def add_flag_bad(data):
data["big"] = data["quantity"] > 2
return data
source = df.copy()
out = source.pipe(add_flag_bad)
print("big" in source.columns) # True: the input was modified
def add_flag(data):
return data.assign(big=data["quantity"] > 2)
source = df.copy()
out = source.pipe(add_flag)
print("big" in source.columns) # False: the input is unchangedWrite pipe-friendly functions so that they build their result with assign, rename and similar methods. If you must use item assignment, start the function with data = data.copy().
This is different from the SettingWithCopyWarning that comes from chained indexing such as df[df["quantity"] > 1]["flag"] = True. That pattern indexes twice and then assigns into a temporary object. Method chaining with assign avoids it, because you never assign into an intermediate result.
Pitfall 4: chains that are too long
A chain has no names for its intermediate results. That helps readability up to a point, then it hurts.
| Problem | Why it happens |
|---|---|
| Hard to find which step failed | The traceback points at the whole statement, not at the failing line inside the parentheses |
| Hard to inspect state | There are no variables to print or open in a debugger |
| Hidden dependencies | Step 12 may rely on a column created in step 3 |
| Mixed purposes | Cleaning, feature building and reporting end up in one block |
A useful rough guide is to stop around eight to ten steps, or when you can no longer describe the chain in one sentence. Split it into named stages, where each stage is a chain or a function with a clear purpose.
def clean(data):
return (
data
.rename(columns={"quantity": "units"})
.query("units > 0")
)
def add_revenue(data):
return data.assign(revenue=lambda d: d["price"] * d["units"])
def summarize(data):
return (
data
.groupby("region", as_index=False)
.agg(total_revenue=("revenue", "sum"), orders=("order_id", "count"))
.sort_values("total_revenue", ascending=False)
)
summary = df.pipe(clean).pipe(add_revenue).pipe(summarize)
print(summary)Each function can be tested alone, and summary still reads top to bottom. You can also store cleaned = df.pipe(clean) when you need to look at that stage.
Pitfall 5: debugging a chain by guessing
When a long chain fails or gives odd numbers, avoid commenting out lines at random. Use the pass-through function from the earlier debugging chapter. It prints information and returns its input unchanged.
def peek(data, label):
print(label, data.shape, list(data.columns))
return data
result = (
df
.pipe(peek, "start")
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe(peek, "with revenue")
.query("revenue > 20")
.pipe(peek, "after filter")
)Remove the peek calls once the problem is found. Leaving them in a shared pipeline adds noise to the output.
Bisecting also works well. Run the first half of the chain into a variable, check it, then add the rest. If you do this often for one pipeline, that pipeline is a candidate for splitting into stages.
When to stop chaining
Chaining suits a sequence of transformations in which each step takes a DataFrame and returns a DataFrame. It fits poorly in several situations.
- Control flow. An
if, a loop over files, or atryblock belongs in a plain statement or a function. Put the decision outside the chain and keep the chain itself linear. - Side effects. Writing to a file or database, or logging, usually belongs at the end as its own statement, not hidden in the middle.
- Reused intermediate results. If two later computations need the same filtered DataFrame, give it a name.
- Multiple outputs. A chain produces one result. If you need a detail table and a summary, build the shared base once and branch from it.
- In-place edits of a few cells. Something like
df.loc[df["order_id"] == 3, "quantity"] = 4is clearer as a statement than as a contrivedassignwithwhere.
Chaining is a style choice, not a rule. A short sequence of plain statements with good variable names is often easier to read than a clever chain, and it is easier to debug.
Quick checklist
Before you commit a chain, check these points.
- No step uses
inplace=True. - Every reference to data inside the chain goes through a lambda or
pipeargument, not through the starting variable. - Functions used with
pipedo not modify their argument. - You can state in one sentence what the chain does.
- Control flow, I/O and reused results sit outside the chain.
Exercise
The following code runs without raising an error but revenue is wrong. Explain why and fix it.
result = (
df
.query("quantity > 1")
.assign(price=lambda d: d["price"] 0.5)
.assign(revenue=df["price"] df["quantity"])
)
Show answer
df["price"] and df["quantity"] refer to the original, unfiltered DataFrame, so revenue ignores the halved price and is aligned on the original index. Use a lambda so the step sees the current DataFrame: .assign(revenue=lambda d: d["price"] * d["quantity"]).
Exercise
A teammate writes def tag(data): data["tag"] = "x"; return data and uses it as df.pipe(tag). What goes wrong, and how do you rewrite the function so the caller's DataFrame stays unchanged?
Show answer
The function assigns a column to the object it received, so the caller's df gains a tag column even though the result is also returned. Rewrite it as def tag(data): return data.assign(tag="x"), or begin the function with data = data.copy().
Exercise
Why does df.rename(columns={"price": "cost"}, inplace=True).query("cost > 5") raise an AttributeError, and what is the smallest change that fixes it?
Show answer
With inplace=True, rename modifies df and returns None, so .query is called on None. Remove inplace=True so rename returns a new DataFrame that .query can use.