pandas-dev/pandas · error · ValueError

axis(= ) out of bounds

Error message

axis(={axis}) out of bounds

What it means

ValueError from SparseArray.cumsum when axis >= ndim (always >= 1 for a 1-D array). The check mimics ndarray behavior which rejects an out-of-range axis before computing.

Solutions

  1. Use arr.cumsum() (axis defaults to 0) or arr.cumsum(axis=0).
  2. Drop the axis kwarg entirely for 1-D sparse arrays.
  3. Materialize to dense and call np.asarray(arr).cumsum(axis=axis) only after validating axis < ndim.

Example fix

// before
arr.cumsum(axis=1)  # raises
// after
arr.cumsum()
Defensive patterns

Strategy: validation

Validate before calling

def safe_cumsum(arr, axis=0):
    if axis >= arr.ndim:
        axis = 0
    return arr.cumsum(axis=axis)

Type guard

def axis_in_bounds(arr, axis) -> bool:
    return axis is None or (0 <= axis < arr.ndim)

Try / catch

try:
    arr.cumsum(axis=axis)
except ValueError as e:
    if 'out of bounds' in str(e):
        out = arr.cumsum(axis=0)
    else:
        raise

Prevention

When it happens

Trigger: arr.cumsum(axis=1) or arr.cumsum(axis=2) on a 1-D SparseArray; forwarding a 2-D axis default from generic code.

Common situations: Code written for DataFrames/2-D arrays reused against a 1-D sparse Series; defaulting axis to a non-zero value.

Related errors


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

Appendix: source

Thrown at pandas/core/arrays/sparse/array.py:1732

        When performing the cumulative summation, any non-NA/null values will
        be skipped. The resulting SparseArray will preserve the locations of
        NaN values, but the fill value will be `np.nan` regardless.

        Parameters
        ----------
        axis : int or None
            Axis over which to perform the cumulative summation. If None,
            perform cumulative summation over flattened array.

        Returns
        -------
        cumsum : SparseArray
        """
        nv.validate_cumsum(args, kwargs)

        if axis is not None and axis >= self.ndim:  # Mimic ndarray behaviour.
            raise ValueError(f"axis(={axis}) out of bounds")

        if not self._null_fill_value:
            return SparseArray(self.to_dense(), fill_value=np.nan).cumsum()

        return SparseArray(
            self.sp_values.cumsum(),
            sparse_index=self.sp_index,
            fill_value=self.fill_value,
        )

    def mean(self, axis: Axis = 0, *args, skipna: bool = True, **kwargs):
        """
        Mean of non-NA/null values.

        Parameters
        ----------
        axis : int, default 0
            Not Used. NumPy compatibility.

View on GitHub (pinned to 3b7651241d)