{"record":{"id":"4273fe25effd2aad","repo":"pandas-dev/pandas","slug":"s-cannot-be-cast-to-bool","errorCode":null,"errorMessage":"{s} cannot be cast to bool","messagePattern":"(.+?) cannot be cast to bool","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/boolean.py","lineNumber":376,"sourceCode":"        true_values: list[str] | None = None,\n        false_values: list[str] | None = None,\n        none_values: list[str] | None = None,\n    ) -> BooleanArray:\n        true_values_union = cls._TRUE_VALUES.union(true_values or [])\n        false_values_union = cls._FALSE_VALUES.union(false_values or [])\n\n        if none_values is None:\n            none_values = []\n\n        def map_string(s) -> bool | None:\n            if s in true_values_union:\n                return True\n            elif s in false_values_union:\n                return False\n            elif s in none_values:\n                return None\n            else:\n                raise ValueError(f\"{s} cannot be cast to bool\")\n\n        scalars = np.array(strings, dtype=object)\n        mask = isna(scalars)\n        scalars[~mask] = list(map(map_string, scalars[~mask]))\n        return cls._from_sequence(scalars, dtype=dtype, copy=copy)\n\n    _HANDLED_TYPES = (np.ndarray, numbers.Number, bool, np.bool_)\n\n    @classmethod\n    def _coerce_to_array(\n        cls, value, *, dtype: DtypeObj, copy: bool = False\n    ) -> tuple[np.ndarray, np.ndarray]:\n        if dtype:\n            assert dtype == \"boolean\"\n        return coerce_to_array(value, copy=copy)\n\n    def _logical_method(self, other, op):\n        assert op.__name__ in {\"or_\", \"ror_\", \"and_\", \"rand_\", \"xor\", \"rxor\"}","sourceCodeStart":358,"sourceCodeEnd":394,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/boolean.py#L358-L394","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"# before\npd.array([\"True\", \"maybe\"], dtype=\"boolean\")  # raises on 'maybe'\n\n# after\npd.Series([\"True\", \"maybe\"]).map({\"True\": True, \"maybe\": None}).astype(\"boolean\")","handlingStrategy":"validation","validationCode":"def parse_bool_strings(strings, true_values=None, false_values=None, none_values=None):\n    import pandas as pd\n    true_values = set(true_values or [])\n    false_values = set(false_values or [])\n    none_values = set(none_values or [])\n    def m(s):\n        if s in true_values or s in {\"True\",\"TRUE\",\"true\",\"1\",\"1.0\"}: return True\n        if s in false_values or s in {\"False\",\"FALSE\",\"false\",\"0\",\"0.0\"}: return False\n        if s in none_values: return None\n        raise ValueError(f\"{s} cannot be cast to bool\")\n    return [m(s) for s in strings]","typeGuard":"def strings_are_bool_parseable(strings, true_values=None, false_values=None, none_values=None) -> bool:\n    try:\n        parse_bool_strings(strings, true_values, false_values, none_values)\n        return True\n    except ValueError:\n        return False","tryCatchPattern":"try:\n    ba = pd.array(strings, dtype=\"boolean\")\nexcept ValueError as e:\n    if \"cannot be cast to bool\" in str(e):\n        mapping = {\"Y\": True, \"N\": False}\n        ba = pd.Series(strings).map(mapping).astype(\"boolean\")\n    else:\n        raise","preventionTips":["Provide true_values/false_values/none_values for custom encodings","Normalize strings (strip, lower-case) before conversion","Inspect unique values to build the mapping"],"tags":["boolean","string-parsing","true-values","read-csv"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}