{"record":{"id":"c2f06d9fe05a5196","repo":"pandas-dev/pandas","slug":"boolean-value-of-an-expression-is-ambiguous","errorCode":null,"errorMessage":"boolean value of an expression is ambiguous","messagePattern":"boolean value of an expression is ambiguous","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"pandas/core/col.py","lineNumber":357,"sourceCode":"            evaluated = []\n            for condition, replacement in caselist:\n                if isinstance(condition, Expression):\n                    condition = condition._eval_expression(df)\n                if isinstance(replacement, Expression):\n                    replacement = replacement._eval_expression(df)\n                evaluated.append((condition, replacement))\n            return ser.case_when(evaluated)\n\n        # Keep repr compact; caselist may be large.\n        repr_str = f\"{self!r}.case_when(...)\"\n        return Expression(func, repr_str)\n\n    def __repr__(self) -> str:\n        return self._repr_str or \"Expr(...)\"\n\n    # Unsupported ops\n    def __bool__(self) -> NoReturn:\n        raise TypeError(\"boolean value of an expression is ambiguous\")\n\n    def __iter__(self) -> NoReturn:\n        raise TypeError(\"Expression objects are not iterable\")\n\n    def __copy__(self) -> NoReturn:\n        raise TypeError(\"Expression objects are not copiable\")\n\n    def __deepcopy__(self, memo: dict[int, Any] | None) -> NoReturn:\n        raise TypeError(\"Expression objects are not copiable\")\n\n\n@set_module(\"pandas\")\ndef col(col_name: Hashable) -> Expression:\n    \"\"\"\n    Generate deferred object representing a column of a DataFrame.\n\n    Any place which accepts ``lambda df: df[col_name]``, such as\n    :meth:`DataFrame.assign` or :meth:`DataFrame.loc`, can also accept","sourceCodeStart":339,"sourceCodeEnd":375,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/col.py#L339-L375","documentation":"Raised by Expression.__bool__ when Python tries to coerce a pandas.api.typing.Expression (produced by pd.col(...)) into a single bool. Expression represents a deferred column operation and evaluates to a per-row Series, so a single truth value is undefined (like NumPy's ambiguous-truth error). The method is typed NoReturn so any bool(ctx) usage fails.","triggerScenarios":"if pd.col('a'): ...; bool(pd.col('a') > 0); using an Expression directly as the test in assert or `and`/`or`; passing an Expression to a function that calls bool() on it (e.g. filter()).","commonSituations":"Treating pd.col('x') like a scalar in a Python conditional; building an Expression inside an if instead of passing it to .loc/.assign/.query where it is evaluated against a DataFrame.","solutions":["Use the Expression where it will be evaluated against a DataFrame: df.loc[pd.col('a') > 0].","If you need a scalar test, evaluate first: result = pd.col('a')._eval_expression(df); then test result.","Replace `if expr:` with the boolean reduction you actually want (e.g. (expr).any())."],"exampleFix":"// before\nexpr = pd.col('speed') > 100\nif expr:\n    ...\n// after\ndf = df.assign(fast=(pd.col('speed') > 100))","handlingStrategy":"type-guard","validationCode":"from pandas.api.typing import Expression\nif isinstance(x, Expression):\n    raise TypeError('Expression must be evaluated against a DataFrame before bool()')","typeGuard":"def is_expression(x) -> bool:\n    from pandas.api.typing import Expression\n    return isinstance(x, Expression)","tryCatchPattern":null,"preventionTips":["Never use a pd.col(...) result in a Python if/and/or/assert.","Evaluate Expressions against a DataFrame before consuming them.","Type-check inputs in generic functions that call bool()."],"tags":["type-error","expression","col","boolean-ambiguous","deferred"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}