Sub topic 14
Validating a Loaded DataFrame
This chapter assumes you can run read_csv and read_excel, know what a DataFrame is, and have met the options for dtypes, missing values and dates from earlier chapters. Here you will check that a loaded DataFrame matches what you expected. The goal is to catch silent parsing problems at load time, before they turn into wrong totals later.
Why loading can succeed and still be wrong
read_csv and read_excel rarely fail on odd data. They guess. A column with one stray text value becomes object. A zip code becomes an integer and loses its leading zero. A date in day-first format is read as month-first when you did not say otherwise. None of these raise an error.
Validation is a short set of checks that run right after loading. It answers four questions:
- Is the shape right (rows and columns)?
- Are the column names and dtypes right?
- Are missing values where you expect them, and only there?
- Do the values fall inside plausible ranges?
The first look: head, info and dtypes
Three calls give you most of what you need.
df.head()shows the first rows. Usedf.tail()as well, because footers such as "Total" rows appear at the end.df.info()prints the row count, each column's dtype, and the count of non-null values.df.dtypesreturns the dtypes as a Series, which you can compare against an expected mapping.
import pandas as pd
from io import StringIO
text = "id,zip,amount\n1,02134,10.5\n2,10001,abc\n3,94105,7.25\n"
df = pd.read_csv(StringIO(text))
print(df.head())
df.info()The output shows amount as object, not float64. That is the signal: one value (abc) is not a number, so pandas kept the whole column as text. It also shows zip as int64, which means 02134 became 2134.
Compare against an expected schema
Reading the output by eye works for one file. For files you load repeatedly, write the expectation down and compare it in code.
import pandas as pd
from io import StringIO
text = "id,zip,amount\n1,02134,10.5\n2,10001,8.0\n"
df = pd.read_csv(StringIO(text), dtype={"zip": "string"})
expected_columns = ["id", "zip", "amount"]
expected_dtypes = {"id": "int64", "zip": "string", "amount": "float64"}
missing = set(expected_columns) - set(df.columns)
extra = set(df.columns) - set(expected_columns)
assert not missing, f"Missing columns: {missing}"
assert not extra, f"Unexpected columns: {extra}"
actual = df.dtypes.astype(str).to_dict()
for col, want in expected_dtypes.items():
assert actual[col] == want, f"{col}: expected {want}, got {actual[col]}"
print("Schema OK")Comparing as a set catches renamed or dropped columns, which often happen when someone edits the source spreadsheet. Converting dtypes with astype(str) makes the comparison simple, because pandas dtype objects and strings do not always compare equal.
Checking shape
df.shape returns (rows, columns). Compare it to a known value or a range. A file that should have about 10,000 rows but loads with 12 usually means a wrong separator, a wrong skiprows, or on_bad_lines="skip" dropping rows.
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO("a,b\n1,2\n3,4\n"))
rows, cols = df.shape
assert cols == 2, f"Expected 2 columns, got {cols}"
assert rows >= 1, "File loaded with no data rows"A one-column result with long strings is the classic sign of a wrong sep. For example, a semicolon file read with the default comma gives a single column named id;price;date.
Missing values
df.isna().sum() counts missing values per column. Pair it with len(df) to get proportions.
import pandas as pd
from io import StringIO
text = "id,price\n1,3.5\n2,N/A\n3,\n"
df = pd.read_csv(StringIO(text), na_values=["N/A"])
print(df.isna().sum())
print(df.isna().mean())
assert df["id"].notna().all(), "id must never be missing"Two things to look for:
- A column that should be complete but has gaps. Here,
idmust always be present. - A column that is entirely missing. This often means a date or number format did not match, and the parser turned every value into
NaNorNaT.
If a marker such as -, ? or n/a appears in the data but not in your na_values, the column will not show as missing. It will show as object. A dtype check and a missing-value check together catch both cases.
Value ranges, categories and duplicates
Correct dtypes do not guarantee sensible values. A numeric age column can contain -1 or 999. Check the ranges that your domain allows.
import pandas as pd
from io import StringIO
text = "id,age,status\n1,34,active\n2,-1,active\n3,41,closed\n3,41,closed\n"
df = pd.read_csv(StringIO(text))
bad_age = df[~df["age"].between(0, 120)]
bad_status = df[~df["status"].isin(["active", "closed", "pending"])]
dupes = df[df.duplicated(subset="id", keep=False)]
print("Out-of-range ages:\n", bad_age)
print("Unknown statuses:\n", bad_status)
print("Duplicate ids:\n", dupes)
print("id unique:", df["id"].is_unique)between is inclusive on both ends by default. duplicated(keep=False) marks every copy of a duplicate, so you see all the rows involved and not only the later ones.
Dates
For a parsed date column, check three things: the dtype is datetime64[ns] (or another datetime dtype), there are no NaT values you did not expect, and the range is plausible.
import pandas as pd
from io import StringIO
text = "id,date\n1,05/01/2024\n2,11/02/2024\n"
df = pd.read_csv(StringIO(text), parse_dates=["date"], date_format="%d/%m/%Y")
assert pd.api.types.is_datetime64_any_dtype(df["date"])
print(df["date"].min(), df["date"].max())
assert df["date"].between("2020-01-01", "2026-12-31").all()The min and max catch a day/month swap. If you read 05/01/2024 as May 1 when it means January 5, individual values look fine, but the range may extend into impossible months or stretch over a different span than the file covers.
Excel-specific checks
Excel files add a few failure modes that CSV files lack.
- Wrong sheet. Confirm
ExcelFile.sheet_namescontains what you expect before parsing. - Header offset. If
skiprowsis off by one, the first data row becomes the header. Checkdf.columnsfirst, and look for names such asUnnamed: 0or values that look like data. - Merged cells and blank rows. Merged cells load as a value followed by
NaN. Fully blank rows load as all-NaNrows. - Trailing totals. Summary rows at the bottom contribute extra rows to sums.
import pandas as pd
from io import BytesIO
buffer = BytesIO()
with pd.ExcelWriter(buffer, engine="openpyxl") as writer:
pd.DataFrame({"region": ["N", "S", None], "sales": [10, 20, None]}).to_excel(
writer, sheet_name="Q1", index=False
)
buffer.seek(0)
df = pd.read_excel(buffer, sheet_name="Q1")
unnamed = [c for c in df.columns if str(c).startswith("Unnamed")]
assert not unnamed, f"Header row probably wrong: {unnamed}"
blank_rows = df.isna().all(axis=1).sum()
print("Fully blank rows:", blank_rows)
df = df.dropna(how="all")
print(df.shape)A reusable validation function
Once you have several checks, put them in one function that collects every problem instead of stopping at the first one. This lets you see all issues in one run.
import pandas as pd
from io import StringIO
def validate(df, columns, dtypes, required=(), ranges=None):
problems = []
missing = [c for c in columns if c not in df.columns]
if missing:
problems.append(f"missing columns: {missing}")
return problems # later checks need these columns
if df.empty:
problems.append("no data rows")
for col, want in dtypes.items():
got = str(df[col].dtype)
if got != want:
problems.append(f"{col}: dtype {got}, expected {want}")
for col in required:
n = int(df[col].isna().sum())
if n:
problems.append(f"{col}: {n} missing values")
for col, (low, high) in (ranges or {}).items():
bad = int((~df[col].between(low, high) & df[col].notna()).sum())
if bad:
problems.append(f"{col}: {bad} values outside [{low}, {high}]")
return problems
text = "id,age\n1,34\n2,-1\n3,\n"
df = pd.read_csv(StringIO(text))
issues = validate(
df,
columns=["id", "age"],
dtypes={"id": "int64", "age": "float64"},
required=["id", "age"],
ranges={"age": (0, 120)},
)
print(issues)This prints ['age: 1 missing values', 'age: 1 values outside [0, 120]']. The notna() guard in the range check keeps missing values from being counted twice. For larger projects, libraries such as pandera and Great Expectations express the same checks declaratively, but plain functions are enough for most loading scripts.
Common mistakes
| Symptom | Likely cause | Check |
|---|---|---|
| Numeric column has dtype `object` | A non-numeric marker in the data | `df[col][pd.to_numeric(df[col], errors="coerce").isna()]` |
| Zip or ID lost leading zeros | Integer inference | `dtype={"col": "string"}` in the load call |
| One wide column | Wrong `sep` | `df.shape`, `df.columns` |
| Date column all `NaT` | Format string does not match | `date_format` and a raw look at the file |
| Fewer rows than expected | `on_bad_lines="skip"` or wrong `skiprows` | Compare with the line count of the source |
| `Unnamed: n` columns | Header row offset or empty columns | `df.columns` |
The first row of the table gives a useful trick. Converting with errors="coerce" turns bad values into NaN, and selecting the rows where the converted result is missing but the original is not shows you exactly which values broke the column.
import pandas as pd
from io import StringIO
df = pd.read_csv(StringIO("amount\n10.5\nabc\n7.25\n"))
converted = pd.to_numeric(df["amount"], errors="coerce")
print(df.loc[converted.isna() & df["amount"].notna(), "amount"])Exercise
A CSV has columns order_id, qty and shipped. After pd.read_csv, df.info() shows qty as object, and df["shipped"].isna().all() is True even though the file has dates in that column. Name one likely cause for each symptom and one check you would run to confirm it.
Show answer
For qty, some cell holds a non-numeric value such as N/A, - or a text note. Confirm it with pd.to_numeric(df["qty"], errors="coerce") and list the rows where the result is missing but the original is not, then add the marker to na_values or clean it. For shipped, the date_format (or the day/month order) probably does not match the file, so every value failed to parse and became NaT. Confirm it by loading the column without parse_dates and comparing a few raw strings with your format string.
Exercise
Write the assertions that would stop a script if the loaded DataFrame df has a duplicate order_id, or any qty outside 1 to 1000.
Show answer
assert df["order_id"].is_unique, "duplicate order_id" and assert df["qty"].between(1, 1000).all(), "qty out of range". If qty may contain missing values, check them separately first, because between returns False for NaN.