pandas-dev/pandas · error · ValueError
{s} cannot be cast to bool
Error message
{s} cannot be cast to bool What it means
BooleanArray._from_sequence_of_strings (boolean.py:376) maps each string to True/False/None using configurable true_values/false_values/none_values sets; any string not in those sets raises ValueError naming the offending token. This is the string-to-boolean parsing path used by read_csv/astype on string data.
Source
Thrown at pandas/core/arrays/boolean.py:376
true_values: list[str] | None = None,
false_values: list[str] | None = None,
none_values: list[str] | None = None,
) -> BooleanArray:
true_values_union = cls._TRUE_VALUES.union(true_values or [])
false_values_union = cls._FALSE_VALUES.union(false_values or [])
if none_values is None:
none_values = []
def map_string(s) -> bool | None:
if s in true_values_union:
return True
elif s in false_values_union:
return False
elif s in none_values:
return None
else:
raise ValueError(f"{s} cannot be cast to bool")
scalars = np.array(strings, dtype=object)
mask = isna(scalars)
scalars[~mask] = list(map(map_string, scalars[~mask]))
return cls._from_sequence(scalars, dtype=dtype, copy=copy)
_HANDLED_TYPES = (np.ndarray, numbers.Number, bool, np.bool_)
@classmethod
def _coerce_to_array(
cls, value, *, dtype: DtypeObj, copy: bool = False
) -> tuple[np.ndarray, np.ndarray]:
if dtype:
assert dtype == "boolean"
return coerce_to_array(value, copy=copy)
def _logical_method(self, other, op):
assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"}View on GitHub (pinned to 71959b8cb9)
Solutions
- Pass explicit true_values/false_values/none_values when reading: pd.read_csv(..., true_values=['Y'], false_values=['N']).
- Pre-map the strings: s.map({'Y': True, 'N': False}).astype('boolean').
- Normalize whitespace/case before conversion: s.str.strip().str.lower().map(...).
- Inspect the unique values with s.unique() and extend the mapping sets accordingly.
Example fix
# before
pd.array(["True", "maybe"], dtype="boolean") # raises on 'maybe'
# after
pd.Series(["True", "maybe"]).map({"True": True, "maybe": None}).astype("boolean") Defensive patterns
Strategy: validation
Validate before calling
def parse_bool_strings(strings, true_values=None, false_values=None, none_values=None):
import pandas as pd
true_values = set(true_values or [])
false_values = set(false_values or [])
none_values = set(none_values or [])
def m(s):
if s in true_values or s in {"True","TRUE","true","1","1.0"}: return True
if s in false_values or s in {"False","FALSE","false","0","0.0"}: return False
if s in none_values: return None
raise ValueError(f"{s} cannot be cast to bool")
return [m(s) for s in strings] Type guard
def strings_are_bool_parseable(strings, true_values=None, false_values=None, none_values=None) -> bool:
try:
parse_bool_strings(strings, true_values, false_values, none_values)
return True
except ValueError:
return False Try / catch
try:
ba = pd.array(strings, dtype="boolean")
except ValueError as e:
if "cannot be cast to bool" in str(e):
mapping = {"Y": True, "N": False}
ba = pd.Series(strings).map(mapping).astype("boolean")
else:
raise Prevention
- Provide true_values/false_values/none_values for custom encodings
- Normalize strings (strip, lower-case) before conversion
- Inspect unique values to build the mapping
When it happens
Trigger: pd.array(['True','maybe'], dtype='boolean'), s.astype('boolean') on a string Series with unrecognized tokens, or read_csv with dtype='boolean' on a column containing values outside true/false/none sets.
Common situations: Datasets with custom boolean encodings ('Y'/'N', 'yes'/'no', 'enabled'/'disabled') without telling pandas the mapping; stray whitespace or case variants; typos in flag columns.
Related errors
- Converting strings to {pa_type} is not implemented.
- Cannot use quantile with bool dtype
- Expected array of boolean type, got {array.type} instead
- cannot pass mask for BooleanArray input
- Need to pass bool-like values
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/4273fe25effd2aad.
Report an issue: GitHub.