pandas-dev/pandas · error · TypeError
unsupported operand type(s) for {res.op}: '{lhs.type}' and '
Error message
unsupported operand type(s) for {res.op}: '{lhs.type}' and '{rhs.type}' What it means
In _maybe_evaluate_binop, after constructing the BinOp the code checks res.has_invalid_return_type (expr.py:511). When the operand types are incompatible for the operator (e.g. numexpr can't add a string array to a bool array, or the dtypes have no valid common result), the flag is set and a TypeError is raised naming the operator and both operand types. This is the type-mismatch guard for binary operations across the supported operator set.
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) == objectView on GitHub (pinned to 71959b8cb9)
Solutions
- Cast the offending columns with astype to a compatible numeric dtype before eval.
- Switch to engine='python' which is more permissive for object-dtype arithmetic.
- Drop or separate the incompatible columns and compute them outside eval.
Example fix
// before
df.eval('a + b') # a is str, b is bool
// after
df['a_num'] = pd.to_numeric(df['a'], errors='coerce')
df.eval('a_num + b') Defensive patterns
Strategy: validation
Validate before calling
def validate_compatible_dtypes(df, expr_cols_per_op) -> None:
for left, right in expr_cols_per_op:
ld, rd = df[left].dtype, df[right].dtype
if ld == object or rd == object:
raise TypeError(
f'cannot combine object-dtype columns {left} ({ld}) and {right} ({rd}); cast first'
)
# or broadly: check dtypes of every column referenced in the expression
Type guard
def columns_are_numeric(df, cols) -> bool:
import pandas.api.types as pt
return all(pt.is_numeric_dtype(df[c]) for c in cols) Try / catch
try:
df.eval(expr)
except TypeError as e:
if 'unsupported operand type' in str(e):
df.eval(expr, engine='python') # python engine is more permissive
else:
raise Prevention
- Cast object/string columns to numeric with pd.to_numeric before arithmetic eval.
- Inspect df.dtypes before passing column expressions to eval.
- Fall back to engine='python' for mixed/object dtype arithmetic.
When it happens
Trigger: df.eval('a + b') where 'a' is object/string dtype and 'b' is bool, or any binary op whose operand return_types the engine deems incompatible. Also mixing datetime with numeric in unsupported ops.
Common situations: Object-dtype columns holding mixed types. String columns participating in arithmetic. Missing dtype conversions after reading CSVs. Version changes in numexpr's accepted type matrix.
Related errors
- Function "{res.name}" does not support keyword arguments
- Column {colname} must have a numeric dtype. Found '{dtype}'
- No masked accumulation defined for dtype {values.dtype.type}
- Cannot compare types {!r} and {!r}
- dtype {data.dtype} cannot be converted to datetime64[ns]
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/f8a1d91a1fe51888.
Report an issue: GitHub.