{"record":{"id":"f8a1d91a1fe51888","repo":"pandas-dev/pandas","slug":"unsupported-operand-type-s-for-res-op-lhs-ty","errorCode":null,"errorMessage":"unsupported operand type(s) for {res.op}: '{lhs.type}' and '{rhs.type}'","messagePattern":"unsupported operand type\\(s\\) for (.+?): '(.+?)' and '(.+?)'","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/computation/expr.py","lineNumber":512,"sourceCode":"        # in that case a + 2 * b will be evaluated using numexpr, and the \"in\"\n        # call will be evaluated using isin (in python space)\n        return binop.evaluate(\n            self.env, self.engine, self.parser, self.term_type, eval_in_python\n        )\n\n    def _maybe_evaluate_binop(\n        self,\n        op,\n        op_class,\n        lhs,\n        rhs,\n        eval_in_python=(\"in\", \"not in\"),\n        maybe_eval_in_python=(\"==\", \"!=\", \"<\", \">\", \"<=\", \">=\"),\n    ):\n        res = op(lhs, rhs)\n\n        if res.has_invalid_return_type:\n            raise TypeError(\n                f\"unsupported operand type(s) for {res.op}: \"\n                f\"'{lhs.type}' and '{rhs.type}'\"\n            )\n\n        if self.engine != \"pytables\" and (\n            (res.op in CMP_OPS_SYMS and getattr(lhs, \"is_datetime\", False))\n            or getattr(rhs, \"is_datetime\", False)\n        ):\n            # all date ops must be done in python bc numexpr doesn't work\n            # well with NaT\n            return self._maybe_eval(res, self.binary_ops)\n\n        if res.op in eval_in_python:\n            # \"in\"/\"not in\" ops are always evaluated in python\n            return self._maybe_eval(res, eval_in_python)\n        elif self.engine != \"pytables\":\n            if (\n                getattr(lhs, \"return_type\", None) == object","sourceCodeStart":494,"sourceCodeEnd":530,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/computation/expr.py#L494-L530","documentation":"Raised by _maybe_evaluate_binop() when the result of applying an operator to two terms reports has_invalid_return_type — meaning the operand types are incompatible for the given operator (e.g., adding a string column to a numeric column, or applying an arithmetic op to unsupported dtypes). The message names the operator and the lhs/rhs types so the developer can identify the mismatch.","triggerScenarios":"df.eval('string_col + numeric_col') where one column is object/str dtype and the other is numeric, and the op is unsupported for that combination; df.query('date_col < some_string') with incompatible types.","commonSituations":"Columns loaded as object dtype due to mixed data; comparing across dtype categories (datetime vs str); operations on categorical columns that degrade to object.","solutions":["Cast columns to compatible dtypes before eval: df['col'] = df['col'].astype('float64').","Rewrite the expression to avoid mixing incompatible types (e.g., separate string handling from numeric ops).","Inspect df.dtypes for the columns involved and fix upstream data loading (e.g., set dtype= in read_csv)."],"exampleFix":"// before\ndf.eval('label_col + count_col')  # label is str, count is int\n\n// after\ndf['count_col'] = df['count_col'].astype(str)\ndf.eval('label_col + count_col')  # string concat","handlingStrategy":"validation","validationCode":"def check_column_dtypes(df, expr):\n    import re\n    cols = re.findall(r'`?([A-Za-z_]\\w*)`?', expr)\n    mismatched = [c for c in cols if c in df.columns]\n    dtypes = {c: df[c].dtype for c in mismatched}\n    return dtypes\n# inspect dtypes and cast before eval if incompatible\nfor c in cols_to_fix:\n    df[c] = df[c].astype('float64')","typeGuard":null,"tryCatchPattern":"try:\n    df.eval(expr)\nexcept TypeError as e:\n    if 'unsupported operand type' in str(e):\n        # cast columns and retry\n        ...","preventionTips":["Check df.dtypes before eval involving arithmetic across columns.","Set dtypes explicitly in read_csv/read_sql.","Cast object columns to numeric/string deliberately."],"tags":["pandas","eval","type-error","dtype-mismatch","binop"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}