Method Chaining
Most pandas methods return a new DataFrame, so you can call the next method directly on the result: df.dropna().sort_values("x").head(). Writing a whole analysis as one chain of steps, wrapped in parentheses with one step per line, gives code that reads top to bottom like a recipe and leaves no half-finished temporary variables behind.
Step by step versus chained
Here's a small analysis written the "step by step" way: clean a table of cinema screenings and find the best-attended films.
import pandas as pd
shows = pd.DataFrame({
"film": ["Dune Two", "Paddington", "dune two ", "Wicked", "Paddington", "Wicked", "Dune Two"],
"seats": [180, 120, 180, 150, 120, 150, 180],
"sold": [171, 64, 150, None, 98, 141, 166],
})
df = shows.dropna(subset=["sold"])
df = df.copy()
df["film"] = df["film"].str.strip().str.title()
df["occupancy"] = df["sold"] / df["seats"]
summary = df.groupby("film")["occupancy"].mean()
summary = summary.sort_values(ascending=False).round(3)
print(summary)film
Wicked 0.940
Dune Two 0.902
Paddington 0.675
Name: occupancy, dtype: float64
And the same logic as one chain:
import pandas as pd
shows = pd.DataFrame({
"film": ["Dune Two", "Paddington", "dune two ", "Wicked", "Paddington", "Wicked", "Dune Two"],
"seats": [180, 120, 180, 150, 120, 150, 180],
"sold": [171, 64, 150, None, 98, 141, 166],
})
summary = (
shows
.dropna(subset=["sold"])
.assign(
film=lambda d: d["film"].str.strip().str.title(),
occupancy=lambda d: d["sold"] / d["seats"],
)
.groupby("film")["occupancy"]
.mean()
.sort_values(ascending=False)
.round(3)
)
print(summary)film
Wicked 0.940
Dune Two 0.902
Paddington 0.675
Name: occupancy, dtype: float64
Each line is one transformation. You can comment out a line to see what changes, and there's no risk of accidentally using a stale intermediate variable.
The key tools
| Instead of… | Chain-friendly method |
|---|---|
df["new"] = ... |
.assign(new=lambda d: ...) |
df = df[df["x"] > 0] |
.query("x > 0") or .loc[lambda d: d["x"] > 0] |
df.columns = [...] |
.rename(columns={...}) / .set_axis([...], axis=1) |
df["x"] = df["x"].astype(int) |
.astype({"x": int}) |
calling your own function f(df) |
.pipe(f) |
The lambda d: in assign and loc receives the DataFrame as it is at that point in the chain, including columns created a step earlier. That's why it's needed: the variable name shows refers to the original, not the intermediate result.
Filtering mid-chain
import pandas as pd
trips = pd.DataFrame({
"city": ["Rome", "Oslo", "Rome", "Kyoto", "Oslo", "Kyoto"],
"nights": [3, 5, 2, 7, 1, 4],
"cost": [540, 1650, 390, 1820, 210, 1100],
})
result = (
trips
.assign(per_night=lambda d: d["cost"] / d["nights"])
.loc[lambda d: d["per_night"] < 300]
.query("nights >= 2")
.sort_values("per_night")
[["city", "nights", "per_night"]]
)
print(result) city nights per_night
0 Rome 3 180.0
2 Rome 2 195.0
3 Kyoto 7 260.0
5 Kyoto 4 275.0
pipe(): your own functions in the chain
pipe(func, *args) calls func(df, *args). It lets you package reusable cleaning steps as functions and still keep the chain readable:
import pandas as pd
def drop_test_rows(df, column="user"):
return df[~df[column].str.startswith("test")]
def add_totals(df):
return df.assign(total=lambda d: d["qty"] * d["price"])
orders = pd.DataFrame({
"user": ["amy", "test_01", "raj", "amy", "test_02"],
"qty": [2, 9, 1, 3, 5],
"price": [4.0, 1.0, 12.5, 4.0, 1.0],
})
report = (
orders
.pipe(drop_test_rows)
.pipe(add_totals)
.groupby("user", as_index=False)["total"].sum()
)
print(report) user total
0 amy 20.0
1 raj 12.5
Debugging a chain
If a chain produces something unexpected, insert a pipe that prints and passes the data through unchanged:
import pandas as pd
def peek(df, label=""):
print(f"[{label}] shape={df.shape}")
return df
scores = pd.DataFrame({"name": ["a", "b", "c", "d"], "score": [55, None, 81, 47]})
passed = (
scores
.pipe(peek, "start")
.dropna()
.pipe(peek, "after dropna")
.query("score >= 50")
.pipe(peek, "after filter")
)
print(passed)[start] shape=(4, 2)
[after dropna] shape=(3, 2)
[after filter] shape=(2, 2)
name score
0 a 55.0
2 c 81.0
Tip: Chains are great for clear, linear transformations. If a chain grows beyond 10–15 steps, split it into a few well-named functions joined with
pipe.
Test yourself
Why wrap a long method chain in parentheses?
- It makes pandas faster
- So the chain can span several lines without backslashes
- It is required for assign()
- It copies the DataFrame
In .assign(total=lambda d: d["a"] + d["b"]), what is d?
- The original DataFrame variable
- The DataFrame at that point in the chain
- A single row
- A column
What does df.pipe(f, 5) do?
- Calls f(5)
- Calls f(df, 5) and returns its result
- Applies f to every cell
- Saves df to a pipe