{"record":{"id":"b252ff12cba3062f","repo":"pandas-dev/pandas","slug":"cannot-compare-types-type-names-0-r-and-type-n","errorCode":null,"errorMessage":"Cannot compare types {type_names[0]!r} and {type_names[1]!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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/array_algos/replace.py#L63-L99","documentation":"TypeError raised in _check_comparison_types during replace: when an element-wise comparison between the array and a value reduces to a scalar bool (not an element-wise array), pandas infers the two types are not comparable and reports the ndarray dtype and the scalar type. This prevents silently returning an all-False mask.","triggerScenarios":"df.replace(non_comparable_value, new_value) where the value's type can't be compared to the column dtype (e.g. replacing a complex number in a string column); regex=False comparisons between incompatible types.","commonSituations":"Looping replace over heterogeneous columns with a single value list; passing None or an unsupported scalar type to replace on a numeric frame.","solutions":["Apply replace per column so each comparison is type-compatible.","Cast the value to match the column dtype before replacing.","Use a regex pattern only on string columns and a separate numeric value on numeric columns."],"exampleFix":"# before\ndf.replace(re.compile('x'), 0)  # on a numeric df\n# after\ndf.apply(lambda c: c.replace(re.compile('x'), 0) if c.dtype == 'object' else c)","handlingStrategy":"validation","validationCode":"def safe_replace(df, to_replace, value):\n    # apply per column so each comparison is type-compatible\n    out = df.copy()\n    for col in out.columns:\n        try:\n            out[col] = out[col].replace(to_replace, value)\n        except TypeError:\n            continue\n    return out","typeGuard":null,"tryCatchPattern":"try:\n    df.replace(to_replace, value)\nexcept TypeError as e:\n    if 'Cannot compare types' in str(e):\n        df.apply(lambda c: c.replace(to_replace, value) if c.dtype == 'object' else c)\n    else:\n        raise","preventionTips":["Apply replace per column for heterogeneous frames.","Match the replacement value type to each column's dtype."],"tags":["replace","type-mismatch","comparison"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-14T00:17:10.932Z"}