KatInterview

Code Review Drill: Three Pandas Helpers in a Data Pipeline

Arrays & HashingModel answer
MediumModel answerArrays & Hashingpythonpandascode-review

Last 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

  1. Walk through each function line by line. Say what it does and what the author was probably trying to achieve.
  2. 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.
  3. 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.