{"record":{"id":"430c64d51fdf0b1c","repo":"pandas-dev/pandas","slug":"n-dimensional-objects-where-n-2-are-not-suppor","errorCode":null,"errorMessage":"N-dimensional objects, where N > 2, are not supported with eval","messagePattern":"N-dimensional objects, where N > 2, are not supported with eval","errorType":"exception","errorClass":"NotImplementedError","httpStatus":null,"severity":"error","filePath":"pandas/core/computation/ops.py","lineNumber":123,"sourceCode":"    def __call__(self, *args, **kwargs):\n        return self.value\n\n    def evaluate(self, *args, **kwargs) -> Term:\n        return self\n\n    def _resolve_name(self):\n        local_name = str(self.local_name)\n        is_local = self.is_local\n        if local_name in self.env.scope and isinstance(\n            self.env.scope[local_name], type\n        ):\n            is_local = False\n\n        res = self.env.resolve(local_name, is_local=is_local)\n        self.update(res)\n\n        if hasattr(res, \"ndim\") and isinstance(res.ndim, int) and res.ndim > 2:\n            raise NotImplementedError(\n                \"N-dimensional objects, where N > 2, are not supported with eval\"\n            )\n        return res\n\n    def update(self, value) -> None:\n        \"\"\"\n        search order for local (i.e., @variable) variables:\n\n        scope, key_variable\n        [('locals', 'local_name'),\n         ('globals', 'local_name'),\n         ('locals', 'key'),\n         ('globals', 'key')]\n        \"\"\"\n        key = self.name\n\n        # if it's a variable name (otherwise a constant)\n        if isinstance(key, str):","sourceCodeStart":105,"sourceCodeEnd":141,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/computation/ops.py#L105-L141","documentation":"Raised in Term._resolve_name when a referenced object has an integral ndim attribute greater than 2. The eval/query engine operates on scalars, Series (1-D), and DataFrames (2-D); higher-dimensional arrays (e.g. 3-D numpy ndarrays) cannot be aligned or broadcast by the evaluation machinery, so a NotImplementedError is raised at name-resolution time.","triggerScenarios":"pd.eval('@a > 0') or df.query('@a') where the @-prefixed local 'a' is a numpy array with ndim >= 3 (e.g. np.zeros((2,2,2))). Also triggered by referencing a 3-D xarray.DataArray or stacked tensor stored in the calling frame's locals/globals.","commonSituations":"Passing multi-dimensional model outputs (image batches, time×channel×feature tensors) into a query expression expecting tabular data. Confusing a DataFrame.values (2-D) with a reshaped 3-D view. Pulling an ndarray from an .npz file and feeding it directly to eval.","solutions":["Flatten or reshape the array to <= 2 dimensions before referencing it: a = a.reshape(a.shape[0], -1).","Convert the array to a DataFrame/Series first: df_a = pd.DataFrame(a); then query against df_a.","Index into a single 2-D slice: pd.eval('@a[:,:,0] > 0') after extracting the slice into a separate local.","Avoid eval/query for >2-D data; use numpy boolean masking directly: a[a > 0]."],"exampleFix":"// before\nimport numpy as np\na = np.zeros((4, 4, 4))\npd.eval(\"@a > 0\")\n\n// after\na2d = a.reshape(a.shape[0], -1)\npd.eval(\"@a2d > 0\")\n# or just\na > 0","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef eval_safe_ndim(obj) -> bool:\n    ndim = getattr(obj, 'ndim', None)\n    return isinstance(ndim, int) and ndim <= 2\n\na = np.zeros((4,4,4))\nassert eval_safe_ndim(a), 'cannot pass >2-D arrays to eval/query'","typeGuard":"import numpy as np\n\ndef is_eval_compatible(obj) -> bool:\n    ndim = getattr(obj, 'ndim', None)\n    if ndim is None:\n        return True  # scalars are fine\n    return isinstance(ndim, int) and ndim <= 2","tryCatchPattern":"try:\n    pd.eval('@a > 0')\nexcept NotImplementedError as e:\n    if 'N-dimensional' in str(e):\n        a2d = a.reshape(a.shape[0], -1)\n        result = a > 0\n    else:\n        raise","preventionTips":["Check array.ndim <= 2 before referencing it in eval/query.","Convert tensors to DataFrames before querying.","Use numpy masking directly for >2-D data."],"tags":["pandas","eval","query","ndim","numpy","dimensionality"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}