Sub topic 12
Inspecting intermediate results without breaking the chain
This chapter assumes you can write a basic chain with assign and query, and that you know how pipe passes a DataFrame to a function. It also assumes you are comfortable with Python functions and lambdas. The goal is to look inside a chain while it runs, without splitting it into temporary variables.
The problem: a chain is one expression
A chain is a single expression. Only its final value is bound to a name, so you never see the frames in the middle. When the result looks wrong, you can't tell which step produced the problem.
The usual fix is to break the chain into variables (step1, step2, and so on), print each one, and rebuild the chain afterwards. That works, but it costs time and it can introduce new mistakes. A better habit is to insert a step into the chain that looks at the data and passes it along unchanged. In this tutorial, that kind of function is called a pass-through function.
The examples below share this setup. Later blocks assume df exists.
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 pass-through pattern
A pass-through function has three properties:
- It takes a DataFrame as its first argument, so
pipecan call it. - It does something observable with the frame, such as printing, logging, checking, or saving it.
- It returns the same frame, so the next step in the chain still receives a DataFrame.
def log_shape(data, label):
print(label, data.shape)
return data
result = (
df
.pipe(log_shape, "start")
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > 20")
.pipe(log_shape, "after filter")
)
print(result)The output is:
start (4, 4)
after filter (2, 5)
order_id region price quantity revenue
2 3 east 15.0 3 45.0
3 4 west 5.0 10 50.0The shape shows two things. assign added one column (4 to 5), and query dropped two rows (4 to 2). If you expected three rows to survive, you now know the problem is in the filter or in the revenue calculation, not in later steps.
Showing more than the shape
The shape is cheap, but sometimes you need to see values. A slightly richer inspector prints a label and the first few rows.
def peek(data, label, rows=3):
print(f"--- {label}: {data.shape[0]} rows, {data.shape[1]} columns")
print(data.head(rows).to_string())
return data
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe(peek, "after assign")
.query("revenue > 20")
)Some choices here are worth noting:
- The label tells you which
pipecall produced which output. With three or four inspectors in one chain, unlabeled output is confusing. to_string()prevents pandas from truncating columns in the middle of your debugging output.head(rows)keeps output short on large frames. Printing a million rows hides the information you wanted.- You can also print
data.dtypes,data.isna().sum(), ordata.indexfor the problem you suspect.
Checking assumptions instead of reading output
Printing requires you to notice the problem. A pass-through function can also check an assumption and stop the chain when it fails.
def expect(data, test, message):
if not test(data):
raise ValueError(f"Check failed: {message}")
return data
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe(expect, lambda d: d["revenue"].gt(0).all(), "revenue must be positive")
.pipe(expect, lambda d: d["order_id"].is_unique, "order_id must be unique")
.query("revenue > 20")
)Both checks pass for this data. If one row had a negative quantity, the chain would stop with ValueError: Check failed: revenue must be positive at the step where the assumption broke. The traceback points into the chain instead of leaving you with a strange result several steps later.
Unlike a print, a check can stay in production code. It documents what the chain expects and fails early.
Capturing snapshots for later
Printing is temporary. If you want to compare two stages after the chain finishes, save them. A pass-through function can store a copy in a dictionary.
snapshots = {}
def capture(data, key):
snapshots[key] = data.copy()
return data
result = (
df
.pipe(capture, "raw")
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe(capture, "with_revenue")
.query("revenue > 20")
)
before = snapshots["with_revenue"]
dropped = before[~before["order_id"].isin(result["order_id"])]
print(dropped)The output is:
order_id region price quantity revenue
0 1 east 10.0 2 20.0
1 2 west 20.0 1 20.0This answers the question "which rows did the filter remove?" Orders 1 and 2 have revenue of exactly 20, and revenue > 20 excludes them. A boundary mistake like this (> where you meant >=) is easy to see once you have the dropped rows and hard to see from the final result alone.
The .copy() matters when later code might modify the frame. Pandas methods return new objects, so most chains are safe, but a custom step that modifies its input would silently change your saved snapshot.
Quick inline inspection
For a throwaway look, you can skip the named function and use a lambda:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.pipe(lambda d: print(d.shape) or d)
.query("revenue > 20")
)print returns None, and None or d evaluates to d, so the frame passes through. This works, but it is cryptic. Use it for a few minutes while debugging and delete it afterwards. For anything you keep, use a named function with a clear label.
Other ways to look inside
| Technique | What it shows | Best for |
|---|---|---|
| `pipe(log_shape, label)` | Row and column counts | Finding which step loses rows or adds columns |
| `pipe(peek, label)` | Actual values | Checking a calculation |
| `pipe(expect, test, message)` | Pass or fail | Permanent guards on assumptions |
| `pipe(capture, key)` | Saved frames | Comparing stages after the run |
| Commenting out steps | Result of a shorter chain | Finding the first step that goes wrong |
Commenting out steps works because the chain sits inside parentheses. Put # in front of a line, and the chain ends one step earlier:
result = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.query("revenue > 20")
# .sort_values("revenue", ascending=False)
# .reset_index(drop=True)
)This cuts the chain from the bottom. It fails if you comment out a step that a later, still-active step depends on. For example, removing assign would break a later query("revenue > 20").
Pitfalls
Forgetting to return the frame
If the function returns None, the next step receives None:
def bad_log(data):
print(data.shape)
df.pipe(bad_log).query("price > 5")This raises AttributeError: 'NoneType' object has no attribute 'query'. The error appears at the step after your inspector, not inside it. When you see NoneType in the middle of a chain, check the most recently added pass-through function first.
Modifying the frame while inspecting
A pass-through function should only observe. Calling data.sort_values("price", inplace=True) inside the inspector changes the frame for every later step, and it makes the debugging code affect the result. If you need a sorted view, print data.sort_values("price") without assigning it back.
Chains that pass through a GroupBy object
After groupby, the object in the chain is a DataFrameGroupBy, not a DataFrame. A function that reads data.shape or data["col"] the way you would on a frame may fail or behave differently. GroupBy objects also have a pipe method, so you can inspect them there. The function must return the grouped object so agg still works.
def group_sizes(grouped):
print(grouped.size())
return grouped
summary = (
df
.assign(revenue=lambda d: d["price"] * d["quantity"])
.groupby("region")
.pipe(group_sizes)
.agg(total_revenue=("revenue", "sum"))
)The inspector prints:
region
east 2
west 2
dtype: int64Leaving inspectors behind
Debug prints in a shared pipeline produce noise, and on a large dataset they cost time. Delete them before you commit, or use the logging module with a debug level so they can be turned off. Keep expect steps that guard real assumptions.
Inspecting the wrong layer
A chain can contain a mistake that is invisible in the frame you print. For example, the index may be non-contiguous after query, which is why the first result above shows index values 2 and 3. If a later step relies on position, check data.index as well, or add reset_index(drop=True).
Putting it together
A reasonable workflow when a chain gives a wrong answer:
- Add
pipe(log_shape, "label")before and after each suspicious step to find where rows or columns change unexpectedly. - Replace the shape check with
peekat the first step that looks wrong, and read the values. - Fix the step, then replace the temporary prints with
expectcalls for assumptions you want to keep. - Remove the remaining prints.
Exercise
A chain contains .pipe(log_columns), and the next step, .query("price > 5"), fails with AttributeError: 'NoneType' object has no attribute 'query'. The function is def log_columns(data): print(list(data.columns)). What is wrong, and how do you fix it?
Show answer
The function has no return statement, so it returns None, and the next step in the chain receives None. Add return data at the end of the function.
Exercise
Write a pass-through function assert_no_nulls(data, column) that raises a ValueError naming the column if it contains any missing values, and otherwise returns the DataFrame unchanged. Show how to use it in a chain right after .assign(revenue=lambda d: d["price"] * d["quantity"]).
Show answer
def assertnonulls(data, column): if data[column].isna().any(): raise ValueError(f"Column {column!r} contains missing values") return data result = ( df .assign(revenue=lambda d: d["price"] * d["quantity"]) .pipe(assertnonulls, "revenue") .query("revenue > 20") )
Exercise
You use capture to save a frame as "with_revenue" before query("revenue > 20"). How do you list the rows the filter removed, and why does capture call .copy()?
Show answer
Compare the saved frame with the result, for example before[~before["order_id"].isin(result["order_id"])]. The copy protects the snapshot from later steps that modify their input in place, so the saved frame keeps the state it had at that point.