Sub topic 1
Why chaining works: methods return new DataFrames
Prerequisites
This chapter assumes basic Python, including functions and lambda expressions. You should also know how to create a pandas DataFrame, select columns, filter rows, and use groupby with basic aggregation.
Why chaining works: methods return new DataFrames
A pandas method usually computes a result and returns a new object. It does not change the original DataFrame unless you explicitly request in-place behavior. Because the returned object is another DataFrame, you can call the next method on it.
import pandas as pd
df = pd.DataFrame({
"region": ["east", "west", "east"],
"sales": [120, 80, 150],
})
renamed = df.rename(columns={"sales": "revenue"})
filtered = renamed.query("revenue > 100")Each variable holds the result of one step. The original df still has a sales column.
A method chain passes each result directly to the next method:
result = (
df
.rename(columns={"sales": "revenue"})
.query("revenue > 100")
.sort_values("revenue", ascending=False)
.reset_index(drop=True)
)
print(result)This chain renames a column, filters rows, sorts the remaining rows, and creates a fresh sequential index.
Formatting a chain so it reads top to bottom
Put the whole expression inside parentheses. Start each method on its own indented line, and place the dot at the beginning of that line. This makes the data flow easy to scan and lets Python continue the expression without backslashes.
Chainable methods you will use most
| Method | Typical purpose |
|---|---|
| `rename` | Change column or index labels |
| `query` | Filter rows using an expression |
| `sort_values` | Order rows by one or more columns |
| `reset_index` | Replace the current index with a simple range |
| `groupby(...).agg(...)` | Build grouped summaries |
groupby returns a grouping object, so it is commonly followed by agg, sum, or another aggregation method before the chain continues with DataFrame methods.
Exercise
Why can .query(...).sort_values(...) appear in one expression?
Show answer
query returns a new DataFrame, and that returned DataFrame has the sort_values method.