Code Review Drill: Three Pandas Helpers in a Data Pipeline
Arrays & HashingModel answerLast updated
Explain what three short pandas helper functions do, then propose and justify improvements to their correctness, speed, readability, robustness and testability.
Scenario
You are doing a live code-review exercise. A reviewer shares three small Python functions from a data-science pipeline that processes transaction records, and asks you to talk through them.
import pandas as pd
def process(df):
out = []
for i in range(len(df)):
if df['amount'][i] > 0:
out.append(df['amount'][i] * 1.1)
else:
out.append(0)
df['adj'] = out
return df
def read_data(path):
data = pd.read_csv(path)
data = data.dropna()
data['date'] = pd.to_datetime(data['date'])
return data
def scale(df, col):
mu = df[col].mean()
sd = df[col].std()
df[col + '_z'] = (df[col] - mu) / sd
return df
Task
- Walk through each function line by line. Say what it does and what the author was probably trying to achieve.
- Identify at least three concrete improvements. Cover several of these angles: correctness, efficiency, naming and readability, documentation, error handling, side effects, separation of concerns, and testing.
- Show how you would rewrite the code, and explain how you would check that the rewrite behaves the same as the original on valid input.
State your assumptions, mention edge cases, and discuss trade-offs where they exist.
Hints
Hint 1
Say what each function does before criticizing it. Then check how `process` indexes the Series (by label or by position) and what happens to the index after `dropna()` has removed rows.
Hint 2
Look for repeated per-element Python work that a single array expression could replace, and for hidden behavior such as mutating the caller's DataFrame or silently discarding rows.
Hint 3
Think about what `scale` returns for a constant column or a column with one value, what `read_data` does with a malformed date or missing column, and how you would unit test each piece with a tiny DataFrame.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Start by describing intent, then group findings by severity: correctness first, then performance, then robustness, then style and testability. A real bug is worth more than a naming nit.
What each function does
process loops over row positions 0..n-1. If amount is positive, it appends amount * 1.1 (a 10% uplift). Otherwise it appends 0. It stores the list in a new column adj, mutating the caller's DataFrame, and returns it.
read_data reads a CSV, drops every row containing any null in any column, converts date to datetime, and returns the result. It mixes I/O, cleaning and type conversion.
scale computes the mean and sample standard deviation (pandas defaults to ddof=1) of one column. It writes a standardized column <col>_z back into the input frame and returns it.
Improvements
-
Label-versus-position bug in
process(most important).df['amount'][i]looks up by index label, not position. Afterread_datarunsdropna(), the index has gaps, sodf['amount'][i]raisesKeyErrorfor a removed label. On a shuffled or non-default index it can silently read the wrong row. Chained indexing like this can also triggerSettingWithCopyWarning. Vectorized operations align by index and avoid the problem entirely. -
Vectorize the loop. The loop is O(n) with heavy interpreter overhead per element, plus two Series lookups per row.
np.where(amount > 0, amount * 1.1, 0.0)is still O(n) but runs in compiled code, typically one to two orders of magnitude faster on large frames. -
Names and magic numbers.
process,scaleandadjsay little. Use names such asadd_adjusted_amount,load_transactionsandadd_zscore. Turn1.1into a documented parameter (markup_rate=0.10). Add type hints and short docstrings stating inputs, outputs and assumptions. -
Side effects. Two functions mutate their argument and also return it, which is confusing. Re-running a notebook cell can double-apply a transform, and callers cannot tell whether their frame changed. Return a new frame (
df.assign(...)ordf.copy()), or mutate and returnNone, but be consistent. -
Separation of concerns in
read_data. Split loading, cleaning and parsing. The cleaning logic then becomes testable on an in-memory DataFrame with no file system. -
Over-aggressive
dropna(). A null in any irrelevant column removes the row. Usesubset=[...]for the required columns and log how many rows were dropped. Silent data loss is a real analytics risk. -
Edge cases and errors.
scale: a constant column givessd == 0, so division producesinforNaN. A column with fewer than two non-null values givessd = NaN. Decide on a documented result, such as all-NaN.read_data: one malformed date aborts the whole load. Useerrors="coerce"and report or drop the failures, or fail fast with a clear message.- Missing columns should raise a descriptive
KeyError. - Non-numeric strings in
amountshould be handled deliberately (pd.to_numeric). - Do not wrap everything in a bare
except. Add context or let the error propagate.
-
Testing. Once functions are pure, each can be tested with a 3 to 5 row DataFrame covering normal, empty, constant, negative and null inputs.
Refactored version
from pathlib import Path
import logging
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
def _require_columns(df: pd.DataFrame, cols: list[str]) -> None:
missing = set(cols) - set(df.columns)
if missing:
raise KeyError(f"Missing required columns: {sorted(missing)}")
def load_transactions(path: str | Path) -> pd.DataFrame:
"""Read raw rows from CSV; no cleaning here."""
return pd.read_csv(path)
def clean_transactions(df: pd.DataFrame,
required: tuple[str, ...] = ("amount", "date")) -> pd.DataFrame:
"""Drop rows missing required fields, parse dates, drop unparseable dates."""
_require_columns(df, list(required))
out = df.dropna(subset=list(required)).copy()
out["date"] = pd.to_datetime(out["date"], errors="coerce")
bad = int(out["date"].isna().sum())
if bad:
logger.warning("Dropping %d rows with unparseable dates", bad)
out = out[out["date"].notna()]
logger.info("Kept %d of %d rows", len(out), len(df))
return out
def add_adjusted_amount(df: pd.DataFrame, markup_rate: float = 0.10,
src: str = "amount", dest: str = "adj") -> pd.DataFrame:
"""Return a copy where dest = src * (1 + rate) if src > 0, else 0."""
_require_columns(df, [src])
amount = pd.to_numeric(df[src], errors="raise")
return df.assign(**{dest: np.where(amount > 0, amount * (1 + markup_rate), 0.0)})
def add_zscore(df: pd.DataFrame, col: str) -> pd.DataFrame:
"""Return a copy with '<col>_z' = (x - mean) / sample std.
If the std is 0 or undefined, the new column is all NaN.
"""
_require_columns(df, [col])
s = df[col]
sd = s.std(ddof=1)
if pd.isna(sd) or sd == 0:
z = pd.Series(np.nan, index=df.index)
else:
z = (s - s.mean()) / sd
return df.assign(**{f"{col}_z": z})
Why the refactor preserves behavior
- Same arithmetic. Positive amounts become
amount * 1.1(with the default rate) and all others become 0, exactly as in the original loop. - Same statistics. The z-score keeps
ddof=1, so values match the original. The only intentional difference is that the degenerate case yieldsNaNinstead ofinf. - Index-safe. Vectorized operations align on labels, so gaps or reordering from earlier steps no longer matter. The original would have crashed or misread rows there.
To validate, run old and new versions on a frame with a clean RangeIndex and assert equality with pd.testing.assert_frame_equal. Then add tests for the cases the old code mishandles: gapped index, constant column, missing column, bad date strings, empty frame.
Complexity
| Function | Time | Space |
|---|---|---|
add_adjusted_amount | O(n), vectorized | O(n) |
clean_transactions | O(n·c) | O(n·c) because of the copy |
add_zscore | O(n), about three passes | O(n) |
The defensive copy costs extra memory. That is fine for typical frames. For very large data you might chunk the CSV read, or mutate in place behind an explicit flag.
Common mistakes in answers
- Only listing style complaints and missing the index-label bug.
- Suggesting
iterrowsorapplyas the "efficient" fix. Both are still row-wise Python. - Changing
ddof(or the zero/negative rule) while refactoring, which silently changes the numbers. - Swallowing exceptions with a bare
exceptto make errors go away. - Not mentioning how the changes would be tested.