pandas or scikit-learn stops with could not convert string to float
Fix it fast
Most common cause, 1 of 3Category labels go straight into a scikit-learn model
Wrap the model in a pipeline whose ColumnTransformer one-hot encodes the text columns and passes the numeric ones through.
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
prep = ColumnTransformer(
[("labels", OneHotEncoder(handle_unknown="ignore"),
make_column_selector(dtype_include=[object, str]))],
remainder="passthrough",
)
model = make_pipeline(prep, LogisticRegression())
model.fit(X_train, y_train)Short answer
ValueError: could not convert string to float means a column still holds text when numbers are expected. The quoted value tells you which kind: a label like 'male' needs encoding before model.fit, '1,234' or '$9.99' needs its symbols removed, and '' or '?' is a missing value pandas did not recognise. Applies to pandas 3.1 and scikit-learn 1.9.
Which cause do you have?
Print every text column with a few of the values that fail numeric parsing. The values themselves show which cause you have, and the empty list means a column is fine. The snippets here use the pandas 3 form include=[object, str]; pandas 2.x refuses any string dtype in select_dtypes, so on 2.x write include=[object] (and dtype_include=object in make_column_selector).
import pandas as pd
df = pd.read_csv("data.csv")
for col in df.select_dtypes(include=[object, str]).columns:
parsed = pd.to_numeric(df[col], errors="coerce")
bad = df.loc[parsed.isna() & df[col].notna(), col]
print(col, bad.unique()[:5])Then find the line you see in this list and open its fix:
- 1Category labels go straight into a scikit-learn model
The failing values are words or codes such as 'male', 'Paris' or 'B12', and the error comes from fit or predict - 2Numbers were saved as text with commas, currency signs or percent marks
The failing values look numeric but carry extra characters: '1,250.00', '$9.99', '12%' or a decimal comma like '3,5' - 3Blanks or placeholders stand where values are missing
The quoted value is empty (''), a space, '?', '-' or a word such as 'unknown'
What does the error look like?
ValueError: could not convert string to float: 'male'ValueError: could not convert string to float: '1,250.00'ValueError: could not convert string to float: ''
Cause 1 of 3
Category labels go straight into a scikit-learn model
You seeThe failing values are words or codes such as 'male', 'Paris' or 'B12', and the error comes from fit or predict
Check
When model.fit raises could not convert string to float on a word, a column of category labels reached an estimator that only does arithmetic on numbers. The scikit-learn guide on categorical features explains that estimators expect numeric input, so such columns are encoded first, for example one-hot, where each label becomes its own 0/1 column.
print(X.select_dtypes(include=[object, str]).columns.tolist())Fix
Wrap the model in a pipeline whose ColumnTransformer one-hot encodes the text columns and passes the numeric ones through. The encoder learns the labels during fit, and handle_unknown='ignore' keeps an unseen label at predict time from raising.
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import OneHotEncoder
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
prep = ColumnTransformer(
[("labels", OneHotEncoder(handle_unknown="ignore"),
make_column_selector(dtype_include=[object, str]))],
remainder="passthrough",
)
model = make_pipeline(prep, LogisticRegression())
model.fit(X_train, y_train)Verify
fit finishes, and model.predict(X_test) returns predictions without the ValueError.
print(model.predict(X_test)[:5])Confirmed by scikit-learn.org
Cause 2 of 3
Numbers were saved as text with commas, currency signs or percent marks
You seeThe failing values look numeric but carry extra characters: '1,250.00', '$9.99', '12%' or a decimal comma like '3,5'
Check
Here the column is numeric in meaning but the file wrote thousands separators or symbols into it, so float() cannot read it. read_csv only strips a thousands separator, or swaps a decimal comma, when you name that character.
print(df["price"].head(10).tolist())Fix
Name the separators when you load the file, or strip the symbols afterwards and convert with to_numeric.
# when loading
df = pd.read_csv("data.csv", thousands=",") # 1,250.00
# df = pd.read_csv("data.csv", sep=";", decimal=",") # 3,5
# after loading (strips $, % and thousands commas; not for decimal commas)
df["price"] = pd.to_numeric(
df["price"].str.replace(r"[$,%]", "", regex=True)
)Verify
The column's dtype is now float64 or int64.
print(df["price"].dtype)Confirmed by pandas.pydata.org
Cause 3 of 3
Blanks or placeholders stand where values are missing
You seeThe quoted value is empty (''), a space, '?', '-' or a word such as 'unknown'
Check
A missing value written as '?' or a single space is plain text to pandas, and float() refuses it. Only the default NaN markers, plus anything you list in na_values, become real missing values when the file is read.
print(df["age"].value_counts(dropna=False).head(10))Fix
List the placeholders in na_values, or turn every unreadable value into NaN with errors='coerce'. Then decide how to fill or drop those rows before training.
df = pd.read_csv("data.csv", na_values=["?", "-", "unknown"])
# or, for one column already loaded
df["age"] = pd.to_numeric(df["age"], errors="coerce")
print(df["age"].isna().sum(), "rows now missing")Verify
The column converts with astype(float), and the count of missing rows matches what you expect.
df["age"].astype(float)Confirmed by pandas.pydata.org
How do I stop it coming back?
- Pass dtype= for numeric columns to read_csv, so a stray symbol fails while the file loads rather than later inside model.fit.
- Keep the encoder inside the same Pipeline as the model, so training and prediction always see the same columns.
- Write the placeholders your data source uses into na_values once, in the loading function every script shares.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine on the same stack: stegnor.com, Menulo, ShopGo.