KatInterview

Improve a Pandas Pipeline: Validation, Testing, and Packaging

SQL & DataModel answer
MediumModel answerSQL & Datapandasrefactoringtesting

Last updated

Fix defects in a CSV processing script, refactor for testability with type hints and input checks, write unit tests, and package with Conda.

You're reviewing a Python script written by a junior analyst. The script computes the sum of a column in a CSV file:

# process.py
import pandas as pd
FILE = 'sales.csv'
output = None

def calculate_sum(column):
 df = pd.read_csv(FILE)
 total = 0
 for val in df[column]:
 if val == '':
 total += 0
 else:
 total += float(val)
 print(total)

calculate_sum('revenue')

Your tasks:

  1. Identify defects and risks. List at least five issues related to correctness, performance, maintainability, or resource handling.

  2. Refactor the code. Rewrite it as a modular, testable library with:

    • Clear function boundaries and no global dependencies
    • Type annotations
    • Input validation using both exceptions and assertions (explain when each is appropriate)
    • Proper error messages for invalid data
  3. Write unit tests. Provide three pytest-style tests covering:

    • Valid numeric inputs
    • Missing or blank values
    • Invalid (non-numeric) data
  4. Environment specification. Create an environment.yml for Conda with Python 3.11 and pinned pandas/pytest versions, plus the commands to set up and activate the environment.

  5. Explain design benefits. Describe how your refactor improves maintainability, makes dependencies explicit, and enables easier testing.

  6. Analyze complexity. State time and space complexity before and after refactoring, and identify any I/O bottlenecks worth addressing at scale.

Hints

Hint 1

How does pandas actually represent empty CSV cells when it reads them? Test with pd.read_csv on a file containing blank cells.

Hint 2

The script runs immediately when imported. How does that affect testability? Consider separating I/O, computation, and the entry point.

Hint 3

For large files, reading the entire CSV into memory at once can be slow or cause out-of-memory errors. Pandas supports chunked reading with the chunksize parameter.