pandas-dev/pandas · error · ValueError

`axis` must be fewer than the number of dimensions

Error message

`axis` must be fewer than the number of dimensions ({ndim})

What it means

Raised by `validate_minmax_axis` when the `axis` argument to min/max/argmin/argmax on a Series or lower-dim object is out of range. Because pandas intentionally ignores invalid axis values for these methods, the validator surfaces the bug explicitly rather than silently returning the wrong result. The check fires when `axis >= ndim` or when the negative wrap (`ndim + axis`) is still negative.

Solutions

  1. Drop the `axis` argument entirely for Series (axis 0 is the only valid value).
  2. For DataFrames, ensure `axis` is 0 or 1 (or None).
  3. Validate `0 <= axis < obj.ndim` before the call.

Example fix

// before
s = pd.Series([1, 2, 3])
s.argmax(axis=1)

// after
s = pd.Series([1, 2, 3])
s.argmax()
Defensive patterns

Strategy: validation

Validate before calling

def valid_axis(axis, ndim):
    return axis is None or (0 <= axis < ndim) or (-ndim <= axis < 0)

Prevention

When it happens

Trigger: `s.argmax(axis=1)` on a Series (ndim=1); `s.min(axis=2)`; `df.min(axis=3)` on a 2D frame; `s.max(axis=-5)` where `-5 + 1 < 0`.

Common situations: Looping over axis as an integer and overshooting the object's dimensionality; refactoring code from DataFrame to Series without dropping the axis arg; off-by-one when computing axis dynamically.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/c792e6c47b1363c8. Report an issue: GitHub.

Appendix: 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 3b7651241d)