Improve a Pandas Pipeline: Validation, Testing, and Packaging
SQL & DataModel answerLast 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:
-
Identify defects and risks. List at least five issues related to correctness, performance, maintainability, or resource handling.
-
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
-
Write unit tests. Provide three pytest-style tests covering:
- Valid numeric inputs
- Missing or blank values
- Invalid (non-numeric) data
-
Environment specification. Create an
environment.ymlfor Conda with Python 3.11 and pinned pandas/pytest versions, plus the commands to set up and activate the environment. -
Explain design benefits. Describe how your refactor improves maintainability, makes dependencies explicit, and enables easier testing.
-
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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Robust CSV Column Aggregation
Strong candidates identify both surface-level bugs and deeper issues with how pandas handles data. They refactor into small, composable functions with explicit contracts, then demonstrate testing and deployment practices.
1. Defects and Risks
Correctness issues:
-
Syntax error. The loop body has incorrect indentation (one space instead of four), causing an
IndentationError. The code won't run. -
Empty-string check never triggers. When
pd.read_csvencounters a blank CSV cell, it converts it toNaN, not an empty string. The conditionval == ''is always false. Whenfloat(NaN)executes, it returnsnan, and the sum becomesnansilently—a critical data bug. -
Invalid values crash without context. If the column contains
"text"or"1,234",float()raisesValueErrorwith no indication of which row or file caused the problem. -
No return value. The function prints instead of returning, making it impossible to test or reuse the result programmatically.
Design and performance:
-
Hard-coded file path and global state.
FILEis a module-level constant, andcalculate_sum('revenue')runs at import time. Any test that imports the module triggers file I/O. The unusedoutputvariable adds confusion. -
Missing column or file gives cryptic errors. A typo in the column name raises a raw
KeyError; a missing file raisesFileNotFoundErrorwith no helpful context. -
Inefficient processing. The function reads the entire file and all columns, then iterates in Python. For large files, this is both slow and memory-intensive. Pandas vectorized operations (
sum()) are orders of magnitude faster. -
Float precision for financial data. Summing floats accumulates rounding error. Production systems handling money should use
Decimalor integer cents. -
No input validation or documentation. There are no type hints, docstrings, or checks that
columnis valid.
2. Refactored Module
Design principles:
- Separate concerns: pure computation (operates on DataFrames), I/O (reads files), and CLI (entry point).
- Explicit dependencies: everything is a parameter—no globals.
- Fail fast with clear messages: validate inputs immediately and provide actionable error context.
# aggregator.py
"""Aggregate numeric columns from CSV files with validation."""
from __future__ import annotations
import argparse
import math
import sys
from pathlib import Path
import pandas as pd
class InvalidDataError(ValueError):
"""Raised when a cell contains non-numeric data that cannot be converted."""
def _convert_to_numeric(series: pd.Series) -> pd.Series:
"""Convert series to float, treating blanks as NaN; raise on unparsable values."""
assert isinstance(series, pd.Series), "internal: must receive a Series"
# Strip whitespace from strings, leave other types unchanged
normalized = series.map(lambda x: x.strip() if isinstance(x, str) else x)
normalized = normalized.replace("", float("nan"))
# Attempt numeric conversion
converted = pd.to_numeric(normalized, errors="coerce")
# Identify cells that were present but became NaN (malformed data)
invalid_mask = normalized.notna() & converted.isna()
if invalid_mask.any():
bad_indices = list(series.index[invalid_mask][:5])
raise InvalidDataError(f"Non-numeric values found at rows {bad_indices}")
assert converted.dtype.kind == "f", "internal: conversion must yield floats"
return converted
def sum_dataframe_column(df: pd.DataFrame, column: str) -> float:
"""
Sum a column from a DataFrame, treating missing/blank values as zero.
Args:
df: DataFrame containing the data
column: Name of the column to sum
Returns:
Sum of all numeric values in the column
Raises:
TypeError: If df is not a DataFrame
ValueError: If column name is empty or sum is non-finite
KeyError: If column doesn't exist
InvalidDataError: If column contains non-numeric data
"""
if not isinstance(df, pd.DataFrame):
raise TypeError(f"Expected DataFrame, got {type(df).__name__}")
if not isinstance(column, str) or not column.strip():
raise ValueError("Column name must be a non-empty string")
if column not in df.columns:
available = ", ".join(df.columns[:5])
raise KeyError(f"Column '{column}' not found. Available: {available}")
numeric_series = _convert_to_numeric(df[column])
result = float(numeric_series.sum(skipna=True))
if not math.isfinite(result):
raise ValueError("Sum is non-finite (possible overflow or inf in data)")
return result
def sum_column_from_csv(
filepath: Path,
column: str,
chunk_size: int = 100_000
) -> float:
"""
Read CSV file in chunks and sum a single column efficiently.
Args:
filepath: Path to the CSV file
column: Column name to aggregate
chunk_size: Number of rows per chunk (for memory efficiency)
Returns:
Total sum across all chunks
"""
if chunk_size <= 0:
raise ValueError("chunk_size must be positive")
filepath = Path(filepath)
if not filepath.is_file():
raise FileNotFoundError(f"File not found: {filepath}")
try:
# Read only the target column to minimize memory usage
reader = pd.read_csv(
filepath,
usecols=[column],
dtype={column: str}, # Force string to control parsing
chunksize=chunk_size
)
except ValueError as e:
# usecols raises ValueError if column doesn't exist
raise KeyError(f"Column '{column}' not found in {filepath}") from e
total = 0.0
with reader:
for chunk_df in reader:
total += sum_dataframe_column(chunk_df, column)
return total
def main(args: list[str] | None = None) -> int:
"""CLI entry point."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("filepath", type=Path, help="Path to CSV file")
parser.add_argument("--column", default="revenue", help="Column to sum")
parsed = parser.parse_args(args)
try:
result = sum_column_from_csv(parsed.filepath, parsed.column)
print(result)
return 0
except (OSError, KeyError, ValueError) as error:
print(f"Error: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
Key improvements:
_convert_to_numerichelper: Distinguishes missing data (blank, NaN) from malformed data (present but unparsable). Reports row indices for debugging.dtype=stron read: Prevents pandas from guessing types, ensuring uniform validation.- Chunked reading:
chunk_sizeparameter enables processing files larger than memory. - Type hints and docstrings: Make the API self-documenting.
Assertions vs. Exceptions:
-
Use assertions for internal invariants—conditions that should never fail if your code is correct. Example:
assert isinstance(series, pd.Series)in_convert_to_numeric. These document programmer contracts and are stripped in optimized mode (python -O). -
Use exceptions (
TypeError,ValueError,KeyError, custom classes) for external inputs—user arguments, file contents, runtime conditions. These must be reliable and catchable. Example: checking ifcolumnexists in the DataFrame.
3. Unit Tests
Tests work with in-memory DataFrames, requiring no file I/O or fixtures:
# test_aggregator.py
import pandas as pd
import pytest
from aggregator import InvalidDataError, sum_dataframe_column
def test_sum_valid_numbers():
"""Sum correctly parses and aggregates numeric strings."""
df = pd.DataFrame({"price": ["10.5", "20", " 5.25 "]})
assert sum_dataframe_column(df, "price") == pytest.approx(35.75)
def test_blank_and_nan_treated_as_zero():
"""Missing, blank, and NaN values are skipped."""
df = pd.DataFrame({
"amount": ["100", None, "", " ", float("nan"), "50"]
})
assert sum_dataframe_column(df, "amount") == pytest.approx(150.0)
def test_invalid_data_raises_with_row_info():
"""Non-numeric values raise InvalidDataError with row indices."""
df = pd.DataFrame({"qty": ["5", "invalid", "10"]})
with pytest.raises(InvalidDataError, match=r"\[1\]"):
sum_dataframe_column(df, "qty")
def test_missing_column_raises_key_error():
"""Requesting a non-existent column raises KeyError."""
df = pd.DataFrame({"a": [1, 2]})
with pytest.raises(KeyError, match="Column 'b' not found"):
sum_dataframe_column(df, "b")
Additional tests to consider: empty DataFrame, all-NaN column, column name with special characters, extremely large values (overflow detection).
4. Environment Setup
environment.yml:
name: csv-aggregator
channels:
- conda-forge
- defaults
dependencies:
- python=3.11.8
- pandas=2.2.1
- pytest=8.1.1
- pip=24.0
Commands:
# Create environment from specification
conda env create -f environment.yml
# Activate the environment
conda activate csv-aggregator
# Verify installation
python -c "import pandas; print(pandas.__version__)"
pytest --version
# Run tests
pytest test_aggregator.py -v
Why pin versions? Ensures reproducible builds across machines and prevents breaking changes from new pandas releases. Update pins periodically after testing.
5. Design Benefits
Maintainability:
- Single Responsibility: Each function has one job.
_convert_to_numerichandles parsing;sum_dataframe_columnhandles aggregation logic;sum_column_from_csvhandles I/O. - No hidden dependencies: All inputs are parameters. Testing and refactoring become straightforward because there's no global state to manage.
Explicit Dependencies:
- The
environment.ymllocks down Python and library versions, preventing "works on my machine" issues. - Type hints document expected types without needing external documentation.
Testability:
- Pure functions (those operating on DataFrames) can be tested with tiny in-memory data, no disk I/O required.
- The CLI (
main) is separated from logic, so you can test the core functions independently. - Dependency injection (passing
filepathandcolumnas arguments) means you can easily mock or substitute test data.
6. Complexity Analysis
Original implementation:
- Time: O(n·m) where n = rows, m = columns. Reads all columns despite needing one. Python loop adds constant-factor overhead vs. vectorized operations.
- Space: O(n·m). Entire DataFrame loaded into memory.
- I/O bottleneck: Single
read_csvcall loads the full file synchronously.
Refactored implementation:
- Time: O(n) per chunk, reading only the target column. Vectorized
sum()is ~100× faster than a Python loop for numeric operations. - Space: O(chunk_size). Memory usage is bounded and configurable.
- I/O bottleneck: Chunked reading enables processing arbitrarily large files. For further optimization at scale:
- Use
pd.read_csv(..., engine='pyarrow')for faster parsing. - Parallelize chunks with
multiprocessingor Dask. - For repeated queries, convert to Parquet (columnar format) for instant column reads.
- Use
Practical impact: On a 10GB CSV with 50 columns, the refactored version uses ~50MB of memory (one chunk of one column) vs. ~10GB (entire file). Parsing time drops from ~120s to ~15s by reading only the needed column.