Sub topic 2
From intermediate variables to a single chain
This chapter assumes you know basic Python (functions, lambdas), can create and inspect a DataFrame, can select columns and filter rows, and have used groupby with simple aggregation. The previous chapter explained why chaining works: most pandas methods return a new object. Here you use that fact to turn a sequence of statements into one expression.
The version with intermediate variables
Suppose you want orders with revenue above 20, largest first. A common first draft saves each 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.assign(revenue=df["price"] * df["quantity"])
step2 = step1.query("revenue > 20")
step3 = step2.sort_values("revenue", ascending=False)
result = step3.reset_index(drop=True)
print(result)This works, but it has costs. You must invent a name for each step. Each name stays in scope after you stop needing it. A later edit can reference step2 when you meant step3, and nothing warns you. The reader also has to follow the variable names to see how the data flows.
The same logic as a chain
Each method returns a DataFrame, so you can call the next method directly on that result. Drop the temporary names and join the calls:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > 20")
.sort_values("revenue", ascending=False)
.reset_index(drop=True)
)
print(result) order_id region price quantity revenue
0 4 west 5.0 10 50.0
1 3 east 15.0 3 45.0The original df is untouched. Only result holds the final DataFrame.
What changed in the assign call
In the variable version you wrote df["price"]. In the chain you wrote lambda d: d["price"]. In a chain there is no name for the intermediate DataFrame, so assign accepts a function. It calls the function with the DataFrame as it exists at that point in the chain and uses the returned values. Here that DataFrame happens to be the original, but the pattern matters later. If a query came before assign, d would be the filtered frame. A later chapter covers this in detail.
Reading a chain
Read a chain from top to bottom as a list of steps:
- Start with
df. - Add a
revenuecolumn. - Keep rows where revenue exceeds 20.
- Sort by revenue, highest first.
- Renumber the index.
Each line does one thing, and the order of lines is the order of operations. Changing the pipeline means adding, removing, or swapping a line.
Common errors when converting
- Referring to a name that no longer exists. Inside
query,"revenue > 20"works only because an earlier step createdrevenue. If you delete that line, the error appears at thequerystep, not where you removed the column. - Using
dfinside a chain step. Writing.assign(x=df["price"] * 2)after aqueryuses the original, unfiltereddf. The row counts then differ and pandas aligns on the index, which can giveNaNvalues without raising an error. Use the lambda form to see the current frame. - Calling a method that returns
None. Some methods change an object in place and returnNone. Putting one in a chain givesAttributeError: 'NoneType' object has no attribute ...on the next call. Pitfalls later in the tutorial cover this.
Converting your own code
To convert a block of statements, work from the top:
- Find a variable that is assigned once and used only in the next line.
- Replace that use with the expression that created it.
- Wrap the whole expression in parentheses and put one method per line.
- Run it and compare against the old result with
result.equals(old_result).
Do this one step at a time rather than rewriting everything at once. If a variable is used in several places, keep it as a variable.
Exercise
A colleague writes high = df.query("price > 8") and then out = high.sort_values("price"). Rewrite these two statements as one chain that stores its result in out, using the same formatting as the examples above.
Show answer
out = (
df
.query("price > 8")
.sortvalues("price")
)
The high variable disappears because `sortvalues is called directly on the DataFrame that query` returns.