Fix ValueError: could not convert string to float by cleaning non-numeric formatting characters (whitespace, currency symbols, thousands-separator commas, or percentage signs) before calling float(s), filtering out empty/placeholder strings like "", "N/A", or "-", and wrapping uncertain inputs in a try ... except ValueError: block—or using pd.to_numeric(..., errors="coerce") when converting entire Pandas columns.
Basic Example
import re
# 1. Clean formatted numeric strings (currency, commas, whitespace) before parsing
raw_price = " $1,249.50 \n"
cleaned = re.sub(r"[^\d.+-eE]", "", raw_price) # Keeps digits, signs, decimal point, and exponent
print(float(cleaned)) # Output: 1249.5
# 2. Safe helper function with fallback for missing/corrupt inputs ("", "N/A", "-")
def safe_float(value: object, default: float | None = None) -> float | None:
if value is None:
return default
text = str(value).strip().replace(",", "")
if not text or text.lower() in {"na", "n/a", "null", "none", "-"}:
return default
try:
return float(text)
except ValueError:
return default
print(safe_float("3,450.75")) # Output: 3450.75
print(safe_float("N/A", 0.0)) # Output: 0.0
print(safe_float("")) # Output: None
Key Details & Edge Cases
- Most common root causes of
ValueError: could not convert string to float: '...':- Empty or whitespace-only strings (
""/" "):float("")always raisesValueError—checkif not s.strip():before parsing. - Thousands-separator commas (
"1,200.50"):float()only accepts ASCII digits, an optional leading+/-, a single decimal point., and scientific notatione/E(plus PEP 515 underscores like"1_200.50"). Strip commas with.replace(",", "")first. - Currency symbols, units, or trailing
%signs ("$49.99","12.5%","45 kg"): Strip known prefixes/suffixes (s.strip(" $%")) or extract the numeric token via regex (re.search(r"[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?", s)). - CSV header rows or sentinel text (
"price","N/A","null","--"): Skip header rows (next(reader)) or handle sentinel placeholders explicitly in your parser.
- Empty or whitespace-only strings (
- European locale decimal commas (
"1.234,56"vs."1,234.56"):- If your input uses a comma as the decimal separator (common in European CSV exports), blindly running
.replace(",", "")turns"12,50"into1250.0instead of12.5! - For European-formatted numbers (
"1.234,56"), remove thousands dots first and then replace the decimal comma with a dot:s.replace(".", "").replace(",", ".")(or uselocale.atof()after configuring the appropriate locale).
- If your input uses a comma as the decimal separator (common in European CSV exports), blindly running
- Bulk conversion in Pandas (
pd.to_numeric(..., errors="coerce")):- Calling
df["col"].astype(float)crashes on the very first unparseable string. Strip formatting characters and usepd.to_numeric(..., errors="coerce")to turn invalid strings intoNaNcleanly:import pandas as pd s = pd.Series(["$1,200.50", "N/A", "$85.00", ""]) numeric_s = pd.to_numeric(s.str.replace(r"[$,]", "", regex=True), errors="coerce") # Result: [1200.50, NaN, 85.00, NaN] (dtype: float64)
- Calling
- Guard against multiple decimal points (
"12.3.4"): Regex character-stripping likere.sub(r"[^\d.]", "", "v1.2.3")leaves"1.2.3", which still failsfloat(). Always pair string cleaning withtry ... except ValueError:so malformed multi-dot strings are caught gracefully.
Comparison of String-to-Float Cleaning & Parsing Strategies
| Input Scenario | Example Raw Input | Recommended Fix | Resulting Output |
|---|---|---|---|
| Empty / placeholder text | "", "N/A", "-" |
Guard check + try ... except ValueError: fallback |
None or 0.0 (no crash) |
| US thousands commas & currency | "$12,450.75" \vert{} float(s.strip().lstrip("$").replace(",", "")) |
12450.75 |
|
| European decimal comma format | "12.450,75" |
float(s.replace(".", "").replace(",", ".")) |
12450.75 |
| Embedded number with units | "42.8 kg" |
re.search(r"[+-]?(?:\d+\.?\d*|\.\d+)", s).group() |
42.8 |
| Dirty Pandas Series / CSV column | ["10.5", "bad", "20"] |
pd.to_numeric(df["col"], errors="coerce") |
Series([10.5, NaN, 20.0]) |
You must log in or register to comment.
