Sub topic 3
Formatting a chain so it reads top to bottom
This chapter assumes you can write a pandas chain on one line and know that methods return new DataFrames. You should also be comfortable with Python's rules for line breaks. Here you will lay a chain out so each step sits on its own line.
The problem with one long line
A chain that works can still be hard to read:
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],
})
result = df.assign(revenue=lambda d: d["price"] * d["quantity"]).query("revenue > 20").sort_values("revenue", ascending=False).reset_index(drop=True)You must scan sideways to find where one step ends and the next begins. Adding a step means editing the middle of a long line, and a diff shows the whole line as changed.
Wrap the chain in parentheses
Python ends a statement at a line break, unless the break is inside brackets. Wrapping the whole expression in parentheses lets you put one method call on each line:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > 20")
.sort_values("revenue", ascending=False)
.reset_index(drop=True)
)
print(result)The layout follows a few conventions:
- The opening parenthesis ends the
result = (line. - The starting object,
df, sits alone on the first line. - Each following line begins with a dot and holds one method call.
- The closing parenthesis sits on its own line, aligned with
result.
Reading from top to bottom now matches the order of execution. The leading dots also make each step's boundary easy to see.
Why the parentheses matter
Without them, Python treats each line as its own statement. Putting the dot at the start of a line then fails:
result = df
.query("price > 5")This raises IndentationError: unexpected indent. If you remove the indentation, Python reports a SyntaxError at the leading dot. The statement result = df ended at the first line break, so the second line makes no sense on its own.
You can also end each line with a backslash. This is fragile, because a single space after the backslash breaks the line. Parentheses are the standard choice.
Comments and one step per line
Inside parentheses, you can put a comment above any step or after it. This is a real advantage over intermediate variables, because each comment sits next to the step it explains:
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],
})
result = (
df
# revenue is needed by the filter below
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > 20") # keep only larger orders
.sort_values("revenue", ascending=False)
.reset_index(drop=True) # number rows 0, 1, 2 again
)
print(result)You can also comment out one line while debugging. Put # in front of a step to see the result without it. Leading dots make this safe, because every line is a complete step.
A method with many arguments can spread over several lines too. Keep the closing bracket aligned with the line that opened it:
summary = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.groupby("region", as_index=False)
.agg(
total_revenue=("revenue", "sum"),
orders=("order_id", "count"),
)
)Common mistakes
- Leaving out the parentheses. This produces the errors shown above.
- Putting a trailing dot at the end of a line. This works inside parentheses, but it hides the start of each step. Pick leading dots and use them everywhere.
- Forgetting the assignment. A chain without
result =computes a new DataFrame and discards it. Nothing changes indf. - Packing several steps onto one line. Keep one step per line, or the benefit of reading downward is lost.
Exercise
The code below raises a SyntaxError. What is the cause, and how do you fix it? summary = df .query("price > 5") .sort_values("price")
Show answer
Python ends the statement summary = df at the first line break, because no bracket is open. The lines that start with a dot are then invalid on their own. Wrap the whole expression in parentheses: summary = ( on the first line, df on the next, the two method lines with leading dots, and a closing ) on its own line.