{"record":{"id":"50d1b437898858a0","repo":"pandas-dev/pandas","slug":"cannot-assign-expression-output-to-target","errorCode":null,"errorMessage":"Cannot assign expression output to target","messagePattern":"Cannot assign expression output to target","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/computation/eval.py","lineNumber":439,"sourceCode":"                        target = target.copy(deep=False)\n                    else:\n                        target = target.copy()\n                except AttributeError as err:\n                    raise ValueError(\"Cannot return a copy of the target\") from err\n            else:\n                target = env.target\n\n            # TypeError is most commonly raised (e.g. int, list), but you\n            # get IndexError if you try to do this assignment on np.ndarray.\n            # we will ignore numpy warnings here; e.g. if trying\n            # to use a non-numeric indexer\n            try:\n                if inplace and isinstance(target, NDFrame):\n                    target.loc[:, assigner] = ret\n                else:\n                    target[assigner] = ret  # pyright: ignore[reportIndexIssue]\n            except (TypeError, IndexError) as err:\n                raise ValueError(\"Cannot assign expression output to target\") from err\n\n            if not resolvers:\n                resolvers = ({assigner: ret},)\n            else:\n                # existing resolver needs updated to handle\n                # case of mutating existing column in copy\n                for resolver in resolvers:\n                    if assigner in resolver:\n                        resolver[assigner] = ret\n                        break\n                else:\n                    resolvers += ({assigner: ret},)\n\n            ret = None\n            first_expr = False\n\n    # We want to exclude `inplace=None` as being False.\n    if inplace is False:","sourceCodeStart":421,"sourceCodeEnd":457,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/computation/eval.py#L421-L457","documentation":"After computing the RHS, eval.py:437 does target[assigner] = ret. For NDFrame in the inplace path it uses .loc[:, assigner]; otherwise it relies on __setitem__ with a string key. If the target type can't take a string-keyed item assignment (int, list, np.ndarray raising IndexError, or other containers raising TypeError), the error is caught at eval.py:438 and re-raised as a clearer ValueError.","triggerScenarios":"pd.eval('a = 1', target=[]), pd.eval('a = 1', target=42), or any target whose __setitem__ rejects string keys. Also np.ndarray targets where the string assigner triggers IndexError.","commonSituations":"Using a non-dict, non-NDFrame object as target. Passing a list expecting it to behave like a namespace. Misconfigured custom resolver objects.","solutions":["Use a dict or DataFrame as the target, both of which support string-key assignment.","For array targets, assign into a dict wrapper and pull values out afterwards.","Use inplace=True with an NDFrame target which routes through .loc[:, assigner]."],"exampleFix":"// before\npd.eval('a = 1', target=[])\n// after\nns = {}\npd.eval('a = 1', target=ns)\nprint(ns['a'])","handlingStrategy":"validation","validationCode":"def validate_target_supports_setitem(target) -> None:\n    if not hasattr(target, '__setitem__'):\n        raise ValueError(\n            f'target {type(target).__name__} cannot accept string-key assignment; '\n            'use a dict or DataFrame'\n        )\n\nvalidate_target_supports_setitem(target)","typeGuard":"def target_supports_str_setitem(target) -> bool:\n    return hasattr(target, '__setitem__')","tryCatchPattern":"try:\n    pd.eval(expr, target=target)\nexcept ValueError as e:\n    if 'assign expression output' in str(e):\n        ns = {}\n        pd.eval(expr, target=ns)  # use a dict target instead\n    else:\n        raise","preventionTips":["Use dict or DataFrame targets for assignment expressions.","Avoid passing lists, ints, or ndarrays as eval targets.","For NDFrame targets, prefer inplace=True which routes through .loc."],"tags":["pandas","eval","target","assignment","setitem"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}