Skip to main content
Albero Academy

The pandas Idiom: Method Chaining

Write clean, readable pipelines with assign, query and pipe — and avoid the SettingWithCopyWarning for good.

Chapter 13Pandas15 min readBeginner friendly
  • #Pandas
  • #Idiom
  • #Chaining

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?

the same logic, two styles
# Choppy: intermediate variables, easy to mix up
tmp = 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 pipeline
result = (
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:

the chaining building blocks
(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:

your function in the chain
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

  1. 01Method chaining expresses analysis as a top-to-bottom pipeline without intermediate variables.
  2. 02assign adds columns immutably; query filters with a readable expression string.
  3. 03Use lambda inside assign/query so each step sees the current (chained) frame.
  4. 04pipe inserts your own function into a chain, keeping custom logic in the flow.
  5. 05Avoid SettingWithCopyWarning with .copy(), .loc[rows,col]=…, and assign — not chained df[mask][col]=….