{"record":{"id":"2b80f54c5a6e5479","repo":"pandas-dev/pandas","slug":"cannot-compare-types-r-and-r","errorCode":null,"errorMessage":"Cannot compare types {!r} and {!r}","messagePattern":"Cannot compare types (.+?) and (.+?)","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/array_algos/replace.py","lineNumber":81,"sourceCode":"    -------\n    mask : array-like of bool\n    \"\"\"\n    if isna(b):\n        return ~mask\n\n    def _check_comparison_types(\n        result: ArrayLike | bool, a: ArrayLike, b: Scalar | Pattern\n    ) -> None:\n        \"\"\"\n        Raises an error if the two arrays (a,b) cannot be compared.\n        Otherwise, returns the comparison result as expected.\n        \"\"\"\n        if is_bool(result) and isinstance(a, np.ndarray):\n            type_names = [type(a).__name__, type(b).__name__]\n\n            type_names[0] = f\"ndarray(dtype={a.dtype})\"\n\n            raise TypeError(\n                f\"Cannot compare types {type_names[0]!r} and {type_names[1]!r}\"\n            )\n\n    if not regex or not should_use_regex(regex, b):\n        # TODO: should use missing.mask_missing?\n        op = lambda x: operator.eq(x, b)\n    else:\n        op = np.vectorize(\n            lambda x: (\n                bool(re.search(b, x))\n                if isinstance(x, str) and isinstance(b, (str, Pattern))\n                else False\n            ),\n            otypes=[bool],\n        )\n\n    # GH#32621 use mask to avoid comparing to NAs\n    if isinstance(a, np.ndarray) and mask is not None:","sourceCodeStart":63,"sourceCodeEnd":99,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/array_algos/replace.py#L63-L99","documentation":"Raised by _check_comparison_types inside compare_or_regex_search (replace.py:81) as a TypeError when a DataFrame/Series.replace operation tries to compare values of incompatible types and the comparison returns a scalar bool rather than an elementwise array. The check fires when the elementwise equality between the array and the replacement target collapses to a single Python bool - an indication the types cannot be meaningfully compared (e.g. comparing a string column to a number).","triggerScenarios":"df.replace(to_replace=..., value=...) where to_replace is a value whose type cannot be compared to the column dtype, e.g. df.replace('x', 0) on a numeric column, or replacing a string in an int column with regex=False. Hit at replace.py:76-83 inside compare_or_regex_search when is_bool(result) and isinstance(a, np.ndarray).","commonSituations":"Calling replace with a to_replace value whose type doesn't match the column dtype; numeric column with a string pattern; replacing across mixed-type columns in one call; building replacement dicts dynamically with mismatched value types.","solutions":["Ensure to_replace and the target column share a comparable type (e.g. replace ints with ints, strings with strings).","Cast the column to the matching dtype first: df['col'] = df['col'].astype(str) before df.replace('x', 'y').","Target the specific column explicitly: df['col'].replace(old, new) so types line up.","If you intended a cross-type replacement, do an explicit astype after the logical replacement rather than asking replace to compare incompatible types."],"exampleFix":"// before\ndf = pd.DataFrame({'a': [1,2,3]})\ndf.replace('x', 0)  # str vs int column\n// after\ndf['a'] = df['a'].astype(str)\ndf.replace('x', '0')","handlingStrategy":"validation","validationCode":"from pandas.api.types import infer_dtype\nfor col in df.columns:\n    inferred = infer_dtype(df[col], skipna=True)\n    if inferred not in ('string','bytes','empty') and isinstance(to_replace, str):\n        raise TypeError(f'cannot compare str to_replace to {col} ({inferred})')","typeGuard":"def replace_types_comparable(df, to_replace) -> bool:\n    from pandas.api.types import infer_dtype\n    target_kind = type(to_replace).__name__\n    for col in df.columns:\n        inferred = infer_dtype(df[col], skipna=True)\n        numeric_kinds = {'integer','floating','mixed-integer-float'}\n        if isinstance(to_replace, str) and inferred in numeric_kinds:\n            return False\n        if isinstance(to_replace, (int, float)) and inferred in {'string'}:\n            return False\n    return True","tryCatchPattern":"try:\n    df.replace(to_replace, value)\nexcept TypeError as e:\n    if 'Cannot compare types' in str(e):\n        df = df.astype(str)\n        df.replace(str(to_replace), str(value))\n    else:\n        raise","preventionTips":["Match to_replace dtype to the column dtype.","Target the specific column rather than the whole frame for cross-type replacements."],"tags":["pandas","replace","type-mismatch","comparison"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}