← Back to Pandas Course | Chapter 13: Performance & Best Practices | Lesson 5 of 6

method chaining

Chaining methods one after another reads like a recipe and avoids a pile of temporary variables.

In this page:

  1. method chaining
Syntax
python
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

python
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
  1. Mixing inplace=True into chains
  2. Overlong unreadable chains
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.