Skilled pandas reads like a pipeline: load → filter → derive → group → sort, each step flowing into the next. Method chaining expresses that without a litter of intermediate variables, and steers you away from the assignment traps beginners hit.
Why chain?
# Choppy: intermediate variables, easy to mix uptmp = df[df["package"] > 5]tmp = tmp.assign(bonus=tmp["package"] * 0.1)result = tmp.groupby("programme")["bonus"].mean()# Chained: reads top-to-bottom as one pipelineresult = (df.query("package > 5").assign(bonus=lambda d: d["package"] * 0.1).groupby("programme")["bonus"].mean())
assign & query
assign adds columns without mutating the original; query filters with a readable string. Both are built for chaining — use a lambda so each step sees the current frame:
(df.query("programme == 'Data' and package > 6").assign(bonus = lambda d: d["package"] * 0.1,tier = lambda d: np.where(d["package"] >= 8, "high", "std"),).sort_values("bonus", ascending=False))
pipe for custom steps
pipe drops your own function into a chain, so even bespoke logic keeps the pipeline flowing:
def add_gst(d, rate=0.18):return d.assign(with_gst=d["price"] * (1 + rate))(df.query("price > 0").pipe(add_gst, rate=0.18).pipe(lambda d: d.sort_values("with_gst")))
The SettingWithCopyWarning
Practice
Rewrite a three-step analysis (filter → add a column → group) as a single chained pipeline using query and assign. Add a custom step with pipe. Trigger a SettingWithCopyWarning with chained assignment, then fix it with .loc or .copy().
Key takeaways
- 01Method chaining expresses analysis as a top-to-bottom pipeline without intermediate variables.
- 02assign adds columns immutably; query filters with a readable expression string.
- 03Use lambda inside assign/query so each step sees the current (chained) frame.
- 04pipe inserts your own function into a chain, keeping custom logic in the flow.
- 05Avoid SettingWithCopyWarning with .copy(), .loc[rows,col]=…, and assign — not chained df[mask][col]=….
