Sub topic 1
Why chaining works: methods return new DataFrames
Method chaining writes df.method_a().method_b().method_c() as one expression. It works because most pandas methods return a new object and leave the original unchanged. This chapter explains that behavior, how to check it yourself, and the cases where it fails. Later chapters build on it with assign and pipe.
Prerequisites
This chapter assumes you can do the following:
- Write Python functions and lambda expressions.
- Create a pandas DataFrame and inspect it with
print,.shape, and.head(). - Select columns and filter rows, for example
df["price"]anddf[df["price"] > 10]. - Use
groupbywith a basic aggregation.
The examples use this DataFrame. Later chapters in this tutorial reuse it.
import pandas as pd
df = pd.DataFrame({
"order_id": [1, 2, 3, 4],
"region": ["east", "west", "east", "west"],
"price": [10.0, 20.0, 15.0, 5.0],
"quantity": [2, 1, 3, 10],
})The rule: a method call produces a value
In Python, a.b().c() calls c on whatever b() returned. A chain therefore works only when every step returns an object that has the next method. Most DataFrame methods return a DataFrame, so the output of one step is a valid input to the next.
The second requirement is that a step does not damage the data it received. Pandas methods such as sort_values, rename, query, and assign build a new DataFrame and return it. The original stays as it was.
sorted_df = df.sort_values("price")
print(sorted_df is df)
print(df["order_id"].tolist())
print(sorted_df["order_id"].tolist())The output is:
False
[1, 2, 3, 4]
[4, 1, 3, 2]sorted_df is a different object from df. The original rows are still in their original order. Because of this, you can keep using df after any chain, and you can run a chain several times from the same starting point.
What this looks like step by step
A chain is a series of values passed along. Each arrow below is a method call, and each box is a separate DataFrame object.
Here is the same transformation written both ways.
# Intermediate variables
step1 = df.sort_values("price", ascending=False)
step2 = step1.query("quantity > 1")
step3 = step2.reset_index(drop=True)
# One chain
step3_chained = (
df
.sort_values("price", ascending=False)
.query("quantity > 1")
.reset_index(drop=True)
)
print(step3.equals(step3_chained))This prints True. The chain creates the same intermediate DataFrames. It just doesn't give them names. The chain is not faster because of that, and it is not a different way of computing. It is a different way of writing the same computation.
Not every method returns a DataFrame
A chain breaks, or ends, when a step returns something else. Check what each method gives back.
examples = {
"sort_values": df.sort_values("price"),
"head": df.head(2),
"column": df["price"],
"sum of column": df["price"].sum(),
"groupby": df.groupby("region"),
"to_csv()": df.to_csv(),
"shape": df.shape,
}
for name, value in examples.items():
print(f"{name:15} -> {type(value).__name__}")The output is:
sort_values -> DataFrame
head -> DataFrame
column -> Series
sum of column -> float64
groupby -> DataFrameGroupBy
to_csv() -> str
shape -> tupleThe practical rule is that you can only call a method that exists on the type you currently hold. This table lists what to expect from common calls.
| Call | Returns | What you can chain next |
|---|---|---|
| `df.rename(...)`, `df.query(...)`, `df.sort_values(...)` | DataFrame | Any DataFrame method |
| `df["col"]` | Series | Series methods such as `.str`, `.sum()`, `.map()` |
| `df.groupby("col")` | DataFrameGroupBy | `.agg(...)`, `.sum()`, `.size()` and similar |
| `df.groupby("col").agg(...)` | DataFrame | Any DataFrame method |
| `df.info()` | `None` (it prints) | Nothing |
| `df.to_csv("file.csv")` | `None` (it writes) | Nothing |
| Any method with `inplace=True` | `None` | Nothing |
Methods that print or write, such as info() and to_csv(path), belong at the end of a chain or outside it. The None return type is the signal that a method is a final step.
The inplace trap
Many pandas methods accept inplace=True. This changes the DataFrame you called the method on and returns None. That behavior breaks chaining because the next call is made on None.
work = df.copy()
result = work.sort_values("price", inplace=True)
print(result)
print(work["order_id"].tolist())
try:
work.sort_values("price", inplace=True).reset_index(drop=True)
except AttributeError as err:
print("AttributeError:", err)The output is:
None
[4, 1, 3, 2]
AttributeError: 'NoneType' object has no attribute 'reset_index'Two things happened here. The call changed work directly, and it returned nothing useful. If you assign the result of an inplace=True call to a variable, the variable holds None, and the DataFrame is lost if you also overwrote its name.
A common beginner mistake is the reverse case, where the method does return a new object and the result is thrown away:
df.sort_values("price")
print(df["order_id"].tolist())This prints [1, 2, 3, 4]. The sorted DataFrame was created, then discarded because nothing captured it. When a chain seems to do nothing, check that its final value is assigned to a name.
The usual fix for both mistakes is the same: do not use inplace=True, and assign the final result.
df = df.sort_values("price").reset_index(drop=True)Rebinding the name df to a new object is not mutation. The old DataFrame is no longer referenced by that name, and Python frees it if nothing else uses it.
Assignment statements mutate
Methods are not the only way to change a DataFrame. Plain assignment changes the object in place and returns nothing:
work = df.copy()
work["revenue"] = work["price"] * work["quantity"]
work.loc[0, "price"] = 99.0Both lines modify work. Neither can sit in the middle of a chain, because an assignment is a statement, not an expression with a value. Method chaining needs a method form of "add a column". That method is assign, which is the subject of a later chapter. It returns a new DataFrame with the extra column, which keeps the original intact.
Is a new object a full copy?
"Returns a new DataFrame" does not always mean "copies all the data right now". Pandas may let the new object share memory with the old one when it can do so safely. What you need to know depends on your pandas version:
- In pandas 3.0 and later, copy-on-write is the default. Any object you derive behaves as an independent copy. Writing to one never changes another. Pandas copies the underlying data only when one of them is actually modified.
- In pandas 2.x, copy-on-write is optional. You can turn it on with
pd.options.mode.copy_on_write = True. Without it, some operations return views, and modifying a view can change the original or raise aSettingWithCopyWarning.
Chains of methods are the safe style under both settings. Each step takes a DataFrame and returns a DataFrame, and you do not write into the intermediate results. The warnings mostly appear when you write into a slice such as df[df["price"] > 10]["quantity"] = 0. A chain avoids this pattern.
Memory is the other concern. Each step creates a new DataFrame, so a long chain on a large table briefly holds several versions. Intermediate objects that nothing refers to can be freed as the chain advances. For most workloads this cost is small compared with the clarity gained. If it becomes a problem, measure it before changing your code.
Summary of the working model
- A method either returns a new object, which makes it chainable, or it changes the object and returns
None. - A chain is valid only if each step returns a type that has the next method.
inplace=Trueand assignment statements mutate the object. They cannot sit inside a chain.- The original DataFrame is unchanged by a chain, so you can rerun it or compare before and after.
Exercise
This code is meant to give you the rows with quantity above 1, sorted by price. It raises an error. Name the cause and rewrite it as a working chain that stores the result in result.
result = df.query("quantity > 1").sortvalues("price", inplace=True).resetindex(drop=True)
Show answer
sort_values(..., inplace=True) sorts in place and returns None, so .reset_index is called on None and raises AttributeError. Remove inplace=True:
result = (
df
.query("quantity > 1")
.sortvalues("price")
.resetindex(drop=True)
)
Exercise
After running df.rename(columns={"price": "unit_price"}) on its own line, you print df.columns and still see price. Why, and how do you keep the renamed DataFrame?
Show answer
rename returns a new DataFrame and leaves df unchanged. The returned object was discarded because it was not assigned. Capture it with renamed = df.rename(columns={"price": "unit_price"}), or rebind the name with df = df.rename(...).
Exercise
Which of these calls can appear in the middle of a chain: df.info(), df.query("price > 5"), df.to_csv("out.csv"), df.groupby("region").agg(total=("price", "sum"))?
Show answer
query and the groupby(...).agg(...) call can appear in the middle, because both return a DataFrame. info() prints and returns None, and to_csv("out.csv") writes a file and returns None, so both can only end a chain or sit outside it.