Sub topic 1
Why chaining works: methods return new DataFrames
Method chaining in pandas depends on one property: most DataFrame methods return a new DataFrame instead of changing the original. This chapter explains that property and shows why it makes a chain possible.
Prerequisites
This chapter assumes you already know:
- Basic Python, including functions and lambda expressions.
- How to create and inspect a pandas DataFrame.
- How to select columns and filter rows.
- The basics of
groupbyand aggregation.
Methods return new objects
Most pandas methods do not change the DataFrame they are called on. They build a new DataFrame with the change applied and return it. The original stays as it was.
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],
})
sorted_df = df.sort_values("price", ascending=False)
print(df["order_id"].tolist())
print(sorted_df["order_id"].tolist())The first line prints [1, 2, 3, 4], so df kept its original row order. The second prints [2, 3, 1, 4], the order of the new object. Calling sort_values did not touch df.
This is the idea of immutability: you treat a DataFrame as a value that you do not modify, and you produce new values from it. pandas does not enforce this everywhere, and some operations still modify an object, but the methods you use in a chain follow it.
A return value is a DataFrame you can keep calling
A method call is an expression. Its result is a DataFrame, so you can call another method on that result immediately. You do not need to store it first.
step1 = df.query("quantity > 1")
step2 = step1.sort_values("price")
step3 = step2.reset_index(drop=True)Each variable holds a new DataFrame. Because step1 is a DataFrame, step1.sort_values(...) is valid. The same is true of the expression df.query("quantity > 1") itself, so the intermediate names are not needed:
result = df.query("quantity > 1").sort_values("price").reset_index(drop=True)
print(result)Each dot passes the result of the previous call to the next method. This is method chaining. The chain works only because every step returns a DataFrame.
What breaks a chain
A chain stops working when a method returns something other than a DataFrame. Two cases are common.
The first is an in-place method. With inplace=True, pandas modifies the object and returns None. Calling a method on None raises an error.
try:
df.copy().sort_values("price", inplace=True).reset_index(drop=True)
except AttributeError as error:
print(error)This prints 'NoneType' object has no attribute 'reset_index'. The sort_values call returned None, so there was nothing to chain on.
The second is a method that returns a different type. df["price"] is a Series, and df.shape is a tuple. After these, the chain continues with Series or tuple methods, not DataFrame methods.
Why this helps
Returning new objects has practical benefits:
- Safety. A step cannot silently change data that other code still uses.
- Readability. The chain reads as a sequence of operations, from the source data to the result.
- Fewer names. You do not need
temp1,temp2, anddf_finalfor steps you will never use again.
The cost is that each step may create a copy, which uses memory. For most analysis work this is acceptable. A later chapter covers when to stop chaining.
Exercise
You run df.sort_values("price", inplace=True).head(2) and get an AttributeError. Why does this fail, and how do you rewrite it so the chain works?
Show answer
With inplace=True, sort_values changes df and returns None, so .head(2) is called on None. Remove inplace=True so the method returns a new DataFrame: df.sort_values("price").head(2).