Below are three complementary strategies—you can mix-and-match depending on how strict you want to be.
1. Fail-fast during the read (dtype=float)
import pandas as pd
try:
df = pd.read_csv(
"path/to/file.tsv",
sep="\t",
header=0, # or header=None + names=[...]
dtype=float # every column must parse to float64
)
except ValueError as e:
raise ValueError(f"🚫 Non-numeric value detected while reading:\n{e}")
print("✅ All cells are floats (dtype=float64)!")
• dtype=float forces every column to be cast to float64.
• If any cell contains a non-numeric token (e.g., "abc" or "—"), read_csv throws a ValueError immediately.
2. Convert after the fact (astype(float) or to_numeric)
import numpy as np
import pandas as pd
df = pd.read_csv("file.tsv", sep="\t")
try:
df = df.astype(float) # one-shot cast
except ValueError: # caught a bad cell somewhere
# Pin-point the offenders
bad = (
df.apply(lambda s: pd.to_numeric(s, errors="coerce"))
.isna() # True where coercion failed
& df.notna() # ignore legit NaN blanks
)
offenders = df[bad] # the actual bad tokens
raise ValueError("Found non-numeric cells:\n" + offenders.stack().to_string())
Why sometimes prefer this?
• You get the DataFrame first, then explicitly decide what to do with non-numeric entries (drop, replace, fix, etc.).
• The little bad mask lets you see exactly which cells misbehave.
3. Programmatic validation (without casting)
import numpy as np
import pandas as pd
df = pd.read_csv("file.tsv", sep="\t")
is_num = df.applymap(np.isreal) # True/False mask
if not is_num.all().all():
bad_cells = df[~is_num]
raise ValueError("Non-numeric cells detected:\n" + bad_cells.stack().to_string())
print("✅ Validation passed: every cell is numeric (int or float).")
• np.isreal (or np.isfinite if you also want to forbid ±inf) checks each individual element.
• Keeps the original dtypes intact and merely verifies content.
Cheat-sheet 📝
• Quick & strict → use dtype=float right inside pd.read_csv.
• Need to repair bad rows → read first, then pd.to_numeric(..., errors="coerce") and investigate the resulting NaNs.
• Just validate, no cast → apply np.isreal or pandas.api.types.is_numeric_dtype column-wise.
Pick the level of strictness that matches your workflow!