{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/computation/eval.py#L421-L457","documentation":"Raised when the assignment to the target fails with TypeError or IndexError during target[assigner] = ret (or target.loc[:, assigner] = ret for inplace NDFrame). This happens when the target object does not support item assignment with a string key (e.g., assigning to a list with a non-integer key), or when the numpy ndarray raises IndexError for the assignment. The original TypeError/IndexError is chained via 'from err'.","triggerScenarios":"Using target=int or target=list where string-key assignment is unsupported: pd.eval('x = 1', target=[]) raises TypeError on list['x']=1. Also triggered when the result shape mismatches the target for numpy arrays (IndexError).","commonSituations":"Passing an incompatible target type; assigning a result whose length/dtype does not match the target's existing structure; using a target that is a tuple (immutable, raises TypeError on assignment).","solutions":["Use a dict or DataFrame as the target — both support string-key assignment: pd.eval('x = 1', target={}).","Ensure the result shape aligns with the target (e.g., the assigned Series length matches the DataFrame rows).","If targeting a numpy array, use an integer index or wrap it in a DataFrame."],"exampleFix":"// before\npd.eval('x = 1', target=[])\n\n// after\npd.eval('x = 1', target={})","handlingStrategy":"type-guard","validationCode":"from collections.abc import MutableMapping\nimport pandas as pd\nif target is not None and not isinstance(target, (MutableMapping, pd.DataFrame, pd.Series)):\n    raise TypeError(f'target {type(target).__name__} must support string-key item assignment')\npd.eval(expr, target=target)","typeGuard":"def supports_string_key_assignment(t) -> bool:\n    try:\n        t['__probe__'] = None\n        del t['__probe__']\n        return True\n    except (TypeError, KeyError):\n        return False","tryCatchPattern":"try:\n    pd.eval(expr, target=target)\nexcept ValueError as e:\n    if 'Cannot assign' in str(e):\n        # switch to a dict target\n        new_target = {}\n        pd.eval(expr, target=new_target)\n    else:\n        raise","preventionTips":["Prefer dict or DataFrame as target.","Verify result shape aligns with target rows.","Avoid passing lists, tuples, or scalars as target."],"tags":["pandas","eval","target","assignment","type-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}