pandas-dev/pandas · error · ValueError
`axis` must be fewer than the number of dimensions ({ndim})
Error message
`axis` must be fewer than the number of dimensions ({ndim}) What it means
Raised by validate_minmax_axis, which guards the axis argument of min/max/argmin/argmax (and the corresponding Series/Index/array methods). For 1-D objects (Series, Index) the only legal axis values are 0 or None; anything else means the operation cannot be mapped to a dimension. The check fires when axis >= ndim or when a negative axis still underflows once wrapped.
Source
Thrown at pandas/compat/numpy/function.py:363
def validate_minmax_axis(axis: AxisInt | None, ndim: int = 1) -> None:
"""
Ensure that the axis argument passed to min, max, argmin, or argmax is zero
or None, as otherwise it will be incorrectly ignored.
Parameters
----------
axis : int or None
ndim : int, default 1
Raises
------
ValueError
"""
if axis is None:
return
if axis >= ndim or (axis < 0 and ndim + axis < 0):
raise ValueError(f"`axis` must be fewer than the number of dimensions ({ndim})")
_validation_funcs = {
"median": validate_median,
"mean": validate_mean,
"min": validate_min,
"max": validate_max,
"sum": validate_sum,
"prod": validate_prod,
}
def validate_func(fname: str, args: tuple[Any, ...], kwargs: dict[str, Any]) -> None:
if fname not in _validation_funcs:
return validate_stat_func(args, kwargs, fname=fname)
validation_func = _validation_funcs[fname]
return validation_func(args, kwargs)View on GitHub (pinned to 71959b8cb9)
Solutions
- Drop or default the axis argument to 0/None when operating on a Series or Index.
- Call the reduction on the DataFrame (df.max(axis=1)) rather than forwarding axis to a Series.
- Validate the axis against obj.ndim before calling .min/.max on it.
Example fix
# before s = pd.Series([1, 2, 3]) s.max(axis=1) # after s.max(axis=0) # or simply s.max()
Defensive patterns
Strategy: validation
Validate before calling
def safe_reduce(obj, axis=0, how='max'):
from pandas.api.types import is_scalar
ndim = getattr(obj, 'ndim', 1)
if axis is not None and (axis >= ndim or (axis < 0 and ndim + axis < 0)):
raise ValueError(f'axis {axis} invalid for ndim={ndim}; defaulting to 0')
return getattr(obj, how)(axis=axis if axis is not None else 0) Type guard
def valid_axis_for(obj, axis) -> bool:
ndim = getattr(obj, 'ndim', 1)
return axis is None or (0 <= axis < ndim) or (-ndim <= axis < 0) Prevention
- Default axis to 0/None when reducing a Series or Index.
- Forward axis only after checking it against obj.ndim.
- Run DataFrame-level reductions rather than looping Series with an axis param.
When it happens
Trigger: Calling .min(axis=1)/.max(axis=1)/.argmin(axis=1)/.argmax(axis=1) on a Series or Index (ndim==1); passing axis=2 to a DataFrame-level min/max through the compat dispatcher; passing a negative axis like axis=-2 to a 1-D Series.
Common situations: Generic helper code that forwards an axis parameter from a DataFrame to a Series without narrowing it; calling Series.min(axis=df._get_axis_number('columns')); refactors that pass axis=1 down to a per-column Series reduction.
Related errors
- cannot diff {type(arr).__name__} on axis={axis}
- Encountered an NA value with skipna=False
- abs(axis) must be less than ndim
- No such keys(s): {pat!r}
- {k} is not a valid identifier
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/c792e6c47b1363c8.
Report an issue: GitHub.