pandas-dev/pandas · error · TypeError

unsupported operand type(s) for

Error message

unsupported operand type(s) for {res.op}: '{lhs.type}' and '{rhs.type}'

What it means

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.

Solutions

  1. Cast columns to compatible dtypes before eval: df['col'] = df['col'].astype('float64').
  2. Rewrite the expression to avoid mixing incompatible types (e.g., separate string handling from numeric ops).
  3. Inspect df.dtypes for the columns involved and fix upstream data loading (e.g., set dtype= in read_csv).

Example fix

// before
df.eval('label_col + count_col')  # label is str, count is int

// after
df['count_col'] = df['count_col'].astype(str)
df.eval('label_col + count_col')  # string concat
Defensive patterns

Strategy: validation

Validate before calling

def check_column_dtypes(df, expr):
    import re
    cols = re.findall(r'`?([A-Za-z_]\w*)`?', expr)
    mismatched = [c for c in cols if c in df.columns]
    dtypes = {c: df[c].dtype for c in mismatched}
    return dtypes
# inspect dtypes and cast before eval if incompatible
for c in cols_to_fix:
    df[c] = df[c].astype('float64')

Try / catch

try:
    df.eval(expr)
except TypeError as e:
    if 'unsupported operand type' in str(e):
        # cast columns and retry
        ...

Prevention

When it happens

Trigger: 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.

Common situations: Columns loaded as object dtype due to mixed data; comparing across dtype categories (datetime vs str); operations on categorical columns that degrade to object.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/f8a1d91a1fe51888. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/computation/expr.py:512

        # in that case a + 2 * b will be evaluated using numexpr, and the "in"
        # call will be evaluated using isin (in python space)
        return binop.evaluate(
            self.env, self.engine, self.parser, self.term_type, eval_in_python
        )

    def _maybe_evaluate_binop(
        self,
        op,
        op_class,
        lhs,
        rhs,
        eval_in_python=("in", "not in"),
        maybe_eval_in_python=("==", "!=", "<", ">", "<=", ">="),
    ):
        res = op(lhs, rhs)

        if res.has_invalid_return_type:
            raise TypeError(
                f"unsupported operand type(s) for {res.op}: "
                f"'{lhs.type}' and '{rhs.type}'"
            )

        if self.engine != "pytables" and (
            (res.op in CMP_OPS_SYMS and getattr(lhs, "is_datetime", False))
            or getattr(rhs, "is_datetime", False)
        ):
            # all date ops must be done in python bc numexpr doesn't work
            # well with NaT
            return self._maybe_eval(res, self.binary_ops)

        if res.op in eval_in_python:
            # "in"/"not in" ops are always evaluated in python
            return self._maybe_eval(res, eval_in_python)
        elif self.engine != "pytables":
            if (
                getattr(lhs, "return_type", None) == object

View on GitHub (pinned to 3b7651241d)