{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/boolean.py#L358-L394","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Pass custom true_values/false_values/none_values through _from_sequence_of_strings (or via read_csv true_values/false_values).","Pre-map the column to True/False/None before constructing the BooleanArray.","Clean the column so only the default accepted tokens remain."],"exampleFix":"// before\npd.array(['Y', 'N', 'unknown'], dtype='boolean')\n// after\nfrom pandas.core.arrays.boolean import BooleanArray\nBooleanArray._from_sequence_of_strings(\n    ['Y', 'N', 'unknown'],\n    dtype=pd.BooleanDtype(),\n    true_values=['Y'], false_values=['N'], none_values=['unknown'],\n)","handlingStrategy":"validation","validationCode":"accepted = {'True', 'TRUE', 'true', '1', '1.0', 'False', 'FALSE', 'false', '0', '0.0'}\nbad = [s for s in strings if s not in accepted and s is not None]\nif bad:\n    raise ValueError(f'unsupported tokens: {bad}')","typeGuard":"def all_tokens_known(strings, true_values, false_values, none_values) -> bool:\n    allowed = set(true_values) | set(false_values) | set(none_values) | {None}\n    return all(s in allowed for s in strings)","tryCatchPattern":"try:\n    pd.array(strings, dtype='boolean')\nexcept ValueError as e:\n    if 'cannot be cast to bool' in str(e):\n        strings = [map_token(s) for s in strings]\n        ...","preventionTips":["Supply true_values/false_values/none_values for non-standard tokens.","Pre-clean string columns to the default accepted set."],"tags":["boolean","string","from-sequence","true-values","false-values"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}