Sub topic 14
Validating a loaded DataFrame
This chapter assumes you can use read_csv and read_excel, set dtype, na_values and parse_dates, and read a DataFrame's info() output. The examples need pandas 2.0 or later.
A successful read_csv call only means the file parsed. It does not mean the data is correct. A wrong delimiter, a misplaced header row or a bad date can all load without any error. Validating right after loading catches these problems before they spread into later steps.
What to check
Run these checks in order. Each one catches a different kind of load failure.
| Check | Tool | What it catches |
|---|---|---|
| Shape | `df.shape` | Skipped rows, truncated files, wrong `nrows` |
| Columns | `df.columns` | Wrong separator, header on the wrong row |
| Types | `df.dtypes`, `df.info()` | Numbers read as text, dates left as strings |
| Missing values | `df.isna().sum()` | Unrecognized markers, failed conversions |
| Values | `df.describe()`, `duplicated()` | Duplicate keys, impossible values |
A reusable validation function
The function below collects every problem into a list instead of stopping at the first one. That way you see all the issues in one run.
import pandas as pd
from io import StringIO
text = (
"id,price,signup\n"
"1,3.5,2024-01-05\n"
"2,,2024-02-11\n"
"3,4.0,not a date\n"
"3,-1.0,2024-03-02\n"
)
df = pd.read_csv(StringIO(text))
df["signup"] = pd.to_datetime(df["signup"], errors="coerce")
def validate(df, required):
problems = []
absent = [c for c in required if c not in df.columns]
if absent:
return [f"missing columns: {absent}"]
if not pd.api.types.is_numeric_dtype(df["price"]):
problems.append("price: not numeric")
if not pd.api.types.is_datetime64_any_dtype(df["signup"]):
problems.append("signup: not a datetime")
for col, n in df[required].isna().sum().items():
if n:
problems.append(f"{col}: {n} missing value(s)")
n_dup = df["id"].duplicated().sum()
if n_dup:
problems.append(f"id: {n_dup} duplicate value(s)")
n_neg = (df["price"] < 0).sum()
if n_neg:
problems.append(f"price: {n_neg} negative value(s)")
return problems
for problem in validate(df, ["id", "price", "signup"]):
print(problem)This prints:
price: 1 missing value(s)
signup: 1 missing value(s)
id: 1 duplicate value(s)
price: 1 negative value(s)The signup count comes from errors="coerce". It turns the unparseable string not a date into NaT (the missing-value marker for dates), so the bad value shows up as a missing value instead of raising an error.
Common mistakes
- Trusting
head()alone. The first rows often look fine while later rows hold the problems. Checkisna().sum()anddescribe()too. - Skipping the dtype check. A single bad entry makes a numeric column load as
object. Nothing fails until you try arithmetic. - Not comparing against the source. Compare
len(df)with the row count you expect, such as the line count of the file minus the header. - Checking only once. Run the same function every time the file is reloaded, because upstream exports change.
To stop a pipeline on bad data, raise an error when the problem list is not empty:
problems = validate(df, ["id", "price", "signup"])
if problems:
raise ValueError("; ".join(problems))Exercise
A file loads without errors, and df.head() looks correct. df["amount"].sum() then raises a TypeError about adding strings. Which check would have found this first, and what is the likely cause?
Show answer
The dtype check, using df.dtypes or df.info(), would have shown amount as object instead of a numeric type. The likely cause is one or more entries that are not numbers, such as "N/A" or a currency symbol, which made pandas read the whole column as text. Fix it with na_values, with dtype, or by converting with pd.to_numeric(..., errors="coerce") and counting the new missing values.