Sub topic 2
From intermediate variables to a single chain
This chapter turns a transformation written as a series of named steps into one method chain. It covers what the chain does at each step, what changes, and the first mistakes people make.
I assume you can create and inspect a DataFrame, select columns, filter rows with a boolean mask, and call sort_values and groupby. I also assume you can read a Python lambda. Later chapters cover assign, pipe, and formatting conventions in detail. Here we only need the idea that a chain is a sequence of method calls.
The starting point: one variable per step
Most pandas code begins as a list of assignments. Each line does one thing and stores the result under a new name.
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],
})
step1 = df.rename(columns={"order_id": "id"})
step2 = step1[step1["quantity"] > 1]
step3 = step2.sort_values("price", ascending=False)
step4 = step3.reset_index(drop=True)
print(step4)The output is:
id region price quantity
0 3 east 15.0 3
1 1 east 10.0 2
2 4 west 5.0 10This code works, and for a short script it is fine. It has costs, though:
- You have to invent a name for every intermediate result. Names like
step1andtmp2say nothing about the data. - The names stay in scope after you need them. Later code can use
step2by accident when it meantstep4. - If you insert a step, you must renumber or rename the variables after it. That is easy to get wrong.
- The reader has to scan every line to learn that only
step4matters.
The same transformation as one chain
Every step above calls a method on the result of the previous step. Because each method returns a DataFrame, you can call the next method on that return value directly, with no name in between.
result = (
df
.rename(columns={"order_id": "id"})
.query("quantity > 1")
.sort_values("price", ascending=False)
.reset_index(drop=True)
)
print(result)The output is identical to the version with four variables. The chain reads top to bottom as a recipe: start with df, rename a column, keep rows where quantity > 1, sort by price, and discard the old index.
Two things changed besides the missing names:
- The wrapping parentheses let Python continue the expression across lines without backslashes. The next chapter covers how to lay these lines out.
- The mask
step1["quantity"] > 1became the string"quantity > 1"passed toquery. We need to look at why.
Why the filter changed form
In the variable version, the filter was step1[step1["quantity"] > 1]. It named step1 twice, once for the object to filter and once for the column to test. In a chain there is no name for the intermediate DataFrame, so you cannot write that expression in the middle of the chain.
You could write df[df["quantity"] > 1], but that refers to the original df, not the current state of the chain. That is wrong whenever an earlier step has changed the data. For example, if a previous step had renamed or created a column, the original df would not have it.
query solves this because it is a method. It receives the current DataFrame as self and evaluates its string against that object's columns. Later chapters show the general solution, a callable that receives the current DataFrame. assign and pipe both use it.
mask_result = df.rename(columns={"order_id": "id"})
# The mask below is evaluated against the original df, not mask_result.
# It works here only because "quantity" was not renamed.
print(df["quantity"] > 1)This is the main rule for writing chains: every expression inside a chain should refer to the DataFrame as it is at that point, not to a variable defined outside.
What happens at each step
Seeing the data flow helps when you debug a chain.
Python evaluates the chain from left to right. First df.rename(...) runs and returns a new DataFrame. .query(...) is called on that new object, and so on. Only the last return value is bound to result. The intermediate DataFrames exist briefly and are then discarded.
This works because these methods do not modify the object they are called on. They build and return a new one. You can check that the source is untouched:
print(df.columns.tolist())
print(df.shape)The output is:
['order_id', 'region', 'price', 'quantity']
(4, 4)The original still has its old column name and all four rows. You can run the chain as many times as you like from the same df and get the same result.
Reading a chain: input, steps, output
A useful habit is to read every chain in three parts.
- Input. The first line, here
df. This is the only external name the chain depends on, apart from names inside lambdas or strings. - Steps. The indented method calls. Each takes the previous result and returns a new one.
- Output. The variable on the left of
=.
Compare this with the variable version, where you must trace step1 through step4 to find the same structure. If you can name the input, the steps, and the output for a chain, you understand it.
The return type can change mid-chain
Each method in a chain must be valid for the object it receives. Most of the methods in this chapter return a DataFrame, so the chain continues. Some methods return something else. Selecting one column with ["price"] gives a Series, and .sum() on that gives a single number.
total_price = (
df
.query("quantity > 1")
["price"]
.sum()
)
print(total_price)The output is 30.0. The chain starts as a DataFrame, becomes a Series, and ends as a float. Methods after ["price"] must be Series methods. A call like .sort_values("price") there would fail, because a Series has no column to sort by.
When a chain fails with an AttributeError or KeyError that surprises you, check what type the previous step returned.
The most common mistake: `inplace=True`
Several pandas methods accept inplace=True. With it, the method changes the existing object and returns None. A None has no methods, so the chain breaks at the next call.
broken = (
df
.sort_values("price", inplace=True)
.reset_index(drop=True)
)This raises:
AttributeError: 'NoneType' object has no attribute 'reset_index'The fix is to drop inplace=True, so that sort_values returns the sorted DataFrame. The same applies to other methods that offer the option.
Comparing the two styles
Neither style is always better. This table summarizes the trade-offs for the example in this chapter.
| Concern | Intermediate variables | Single chain |
|---|---|---|
| Names to invent | One per step | One for the result |
| Leftover variables in scope | All of them | None |
| Reading order | Follow the names | Top to bottom |
| Inserting or removing a step | Edit names after it | Add or delete one line |
| Inspecting a middle result | Print any variable | Needs a technique (see the debugging chapter) |
| Filtering on the current state | Name the variable twice | Needs `query` or a callable |
The chain wins on structure and loses some convenience in inspection. Later chapters give you tools to recover that convenience.
Converting existing code to a chain
Use this procedure when you convert a block of intermediate variables.
- Check that each variable is used only by the next line. If
step2is also used by some other code, it needs to stay a variable. - Replace the second line's use of
step1with the first line's expression, then repeat down the block. - Where a step indexes the previous result by name, as in
step1[step1["quantity"] > 1], replace it with a method that accepts the current state, such asquery. - Wrap the whole expression in parentheses.
- Run the old and new versions and compare the results.
For the last step, equals gives a precise check:
old = (
df.rename(columns={"order_id": "id"})
.pipe(lambda d: d[d["quantity"] > 1])
.sort_values("price", ascending=False)
.reset_index(drop=True)
)
new = (
df
.rename(columns={"order_id": "id"})
.query("quantity > 1")
.sort_values("price", ascending=False)
.reset_index(drop=True)
)
print(old.equals(new))The output is True. The first version uses pipe with a lambda only to illustrate the "callable that receives the current DataFrame" idea. You will meet pipe properly in a later chapter, so for now treat it as a way to run a function on the current state.
Summary of the working model
- A chain works because the methods return new DataFrames, so each call can start from the previous result.
- The chain is read left to right, and only the final value is stored.
- Expressions inside a chain must refer to the current DataFrame, not to the original variable.
- The type can change along the chain, so check what each step returns.
- Avoid
inplace=True, because it returnsNoneand ends the chain.
Exercise
This code is meant to return the rows with price above 8, sorted by price. It raises an AttributeError. Explain why, and rewrite it so it works. result = ( df .query("price > 8") .sortvalues("price", inplace=True) .resetindex(drop=True) )
Show answer
sortvalues with inplace=True sorts the DataFrame in place and returns None, so .resetindex is called on None. Remove inplace=True: result = ( df .query("price > 8") .sortvalues("price") .resetindex(drop=True) )
Exercise
Convert these steps to a single chain, and name the input, the steps, and the output. a = df.rename(columns={"quantity": "qty"}) b = a[a["qty"] >= 3] c = b.sort_values("qty")
Show answer
result = ( df .rename(columns={"quantity": "qty"}) .query("qty >= 3") .sortvalues("qty") ) The input is df, the steps are rename, query, and sortvalues, and the output is result. The query string uses the new name qty because it runs on the renamed DataFrame, not on the original df.