pandas-dev/pandas · error · NotImplementedError
N-dimensional objects, where N > 2, are not supported with e
Error message
N-dimensional objects, where N > 2, are not supported with eval
What it means
Raised by Term._resolve_name in pandas.core.computation.ops when a name resolved from the eval/query scope has ndim > 2. pandas' eval engine only operates on scalars, Series (1D), and DataFrames (2D); anything of higher dimensionality (e.g. a 3D numpy array or an xarray.DataArray) cannot be mapped to a term. It is raised as NotImplementedError after the value is resolved from locals/globals. The check uses hasattr(res,'ndim') and isinstance(res.ndim, int).
Source
Thrown at pandas/core/computation/ops.py:123
def __call__(self, *args, **kwargs):
return self.value
def evaluate(self, *args, **kwargs) -> Term:
return self
def _resolve_name(self):
local_name = str(self.local_name)
is_local = self.is_local
if local_name in self.env.scope and isinstance(
self.env.scope[local_name], type
):
is_local = False
res = self.env.resolve(local_name, is_local=is_local)
self.update(res)
if hasattr(res, "ndim") and isinstance(res.ndim, int) and res.ndim > 2:
raise NotImplementedError(
"N-dimensional objects, where N > 2, are not supported with eval"
)
return res
def update(self, value) -> None:
"""
search order for local (i.e., @variable) variables:
scope, key_variable
[('locals', 'local_name'),
('globals', 'local_name'),
('locals', 'key'),
('globals', 'key')]
"""
key = self.name
# if it's a variable name (otherwise a constant)
if isinstance(key, str):View on GitHub (pinned to 71959b8cb9)
Solutions
- Reduce the operand to 1D/2D before eval: reshape with .ravel(), .reshape(-1), .squeeze(), or stack the array so ndim <= 2.
- If the goal is element-wise math on an N-D array, skip pd.eval and use numpy/ufuncs directly (e.g. np.sin(a)).
- If the N-D object is a column of arrays, flatten/explode it first (df['a'].explode() or np.stack) so each cell is scalar.
- For multi-index DataFrames, reset_index() or stack/unstack to bring the frame back to 2D before querying.
Example fix
# before
import numpy as np, pandas as pd
a = np.zeros((2, 2, 2))
pd.eval('@a + 1', local_dict={'a': a}) # NotImplementedError
# after
pd.eval('@a_flat + 1', local_dict={'a_flat': a.ravel()})
# or just use numpy:
a + 1 Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
def safe_eval_operand(value):
ndim = getattr(value, 'ndim', None)
if isinstance(ndim, int) and ndim > 2:
raise ValueError(f'operand has ndim={ndim}; pandas.eval only supports ndim<=2')
return value
# before pd.eval('@a + 1', local_dict={'a': a}):
safe_eval_operand(a) Type guard
from typing import Any
import numpy as np
def is_eval_safe_array(obj: Any) -> bool:
ndim = getattr(obj, 'ndim', None)
return isinstance(ndim, int) and ndim <= 2
Try / catch
try:
result = pd.eval(expr, local_dict=locals())
except NotImplementedError as e:
if 'N-dimensional' in str(e):
# flatten or fall back to numpy
result = None
else:
raise Prevention
- Keep eval/query operands to scalars, Series, or 2D DataFrames.
- Pre-flatten N-D arrays with .ravel()/.reshape(-1) before passing as @locals.
- For N-D math, use numpy ufuncs directly instead of pd.eval.
When it happens
Trigger: Calling pd.eval(), DataFrame.eval(), or DataFrame.query() with a local variable (via @var) or a column whose value is an object with ndim > 2, e.g. pd.eval('@a', local_dict={'a': np.zeros((2,2,2))}) or df.query('a > 0') where column 'a' holds 3D ndarrays per row.
Common situations: Passing a 3D numpy array, an xarray.DataArray, or a stacked Panel-like object into an eval expression. Also occurs when a column was constructed from nested arrays whose elements are themselves multi-dimensional, or when migrating old Panel-based code to modern pandas.
Related errors
- The '@' prefix is only supported by the pandas parser
- The '@' prefix is not allowed in top-level eval calls. pleas
- expr must be a string to be evaluated, {type(expr)} given
- multi-line expressions are only valid in the context of data
- Multi-line expressions are only valid if all expressions con
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/430c64d51fdf0b1c.
Report an issue: GitHub.