method chaining
Chaining methods one after another reads like a recipe and avoids a pile of temporary variables.
In this page:
Syntax
result = (df
.query("condition")
.assign(new_column=lambda d: expression)
.groupby("column")
.agg("function_name"))
method chaining
Because most methods return a new DataFrame, you can chain them: df.query(...).assign(...).sort_values(...). Wrap the chain in parentheses to split it over lines. pipe() lets you insert your own functions into a chain.
Note:
Wrap the whole chain in parentheses to break lines without backslashes.
Example: method chaining
import pandas as pd
df = pd.DataFrame({"name": ["Ann", "Bob", "Cy"], "price": [10, 25, 40], "qty": [3, 1, 2]})
result = (
df.assign(total=lambda d: d["price"] * d["qty"])
.query("total > 25")
.sort_values("total", ascending=False)
.reset_index(drop=True)
)
print(result)
# Output:
# name price qty total
# 0 Cy 40 2 80
# 1 Ann 10 3 30
Related Topics
Common Mistakes
- Mixing inplace=True into chains
- Overlong unreadable chains
- Losing the intermediate result you need for debugging
Chapter Summary
- Methods return new DataFrames
- Chain them for readability
- Parentheses allow line breaks
- pipe inserts custom functions
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: