pandas-dev/pandas · error · ValueError

cannot be cast to bool

Error message

{s} cannot be cast to bool

What it means

Raised by BooleanArray._from_sequence_of_strings (via map_string) when a string is not in the configured true_values, false_values, or none_values sets. The default accepted strings are {'True','TRUE','true','1','1.0'} for True, {'False','FALSE','false','0','0.0'} for False, plus any custom values supplied. Any other token is rejected.

Solutions

  1. Pass custom true_values/false_values/none_values through _from_sequence_of_strings (or via read_csv true_values/false_values).
  2. Pre-map the column to True/False/None before constructing the BooleanArray.
  3. Clean the column so only the default accepted tokens remain.

Example fix

// before
pd.array(['Y', 'N', 'unknown'], dtype='boolean')
// after
from pandas.core.arrays.boolean import BooleanArray
BooleanArray._from_sequence_of_strings(
    ['Y', 'N', 'unknown'],
    dtype=pd.BooleanDtype(),
    true_values=['Y'], false_values=['N'], none_values=['unknown'],
)
Defensive patterns

Strategy: validation

Validate before calling

accepted = {'True', 'TRUE', 'true', '1', '1.0', 'False', 'FALSE', 'false', '0', '0.0'}
bad = [s for s in strings if s not in accepted and s is not None]
if bad:
    raise ValueError(f'unsupported tokens: {bad}')

Type guard

def all_tokens_known(strings, true_values, false_values, none_values) -> bool:
    allowed = set(true_values) | set(false_values) | set(none_values) | {None}
    return all(s in allowed for s in strings)

Try / catch

try:
    pd.array(strings, dtype='boolean')
except ValueError as e:
    if 'cannot be cast to bool' in str(e):
        strings = [map_token(s) for s in strings]
        ...

Prevention

When it happens

Trigger: pd.array(['True', 'False', 'maybe'], dtype='boolean'); Series.astype('boolean') on a string column with non-standard tokens; read_csv with dtype='boolean' on a column containing 'Y'/'N' without specifying true_values/false_values.

Common situations: Survey data with 'Y'/'N'; regional true/false spellings; uppercase variants not in the defaults; columns with sentinel strings like 'unknown' that should map to NA.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/4273fe25effd2aad. Report an issue: GitHub.

Appendix: 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 3b7651241d)