pandas-dev/pandas · error · IndexError

index {key} is out of bounds for axis 0 with size {n}

Error message

index {key} is out of bounds for axis 0 with size {n}

What it means

Raised in __setitem__ on the integer-key path when the resolved index is outside [0, n). Negative indices are normalized by adding n, so both overly-negative and too-large indices land here.

Source

Thrown at pandas/core/arrays/arrow/array.py:2892

        if com.is_null_slice(key):
            # fast path (GH50248)
            if (
                isinstance(value, (pa.Array, pa.ChunkedArray))
                and value.type == self._pa_array.type
                and len(value) == len(self)
            ):
                data = value
            else:
                data = self._if_else(True, value, self._pa_array)

        elif is_integer(key):
            # fast path
            key = cast("int", key)
            n = len(self)
            if key < 0:
                key += n
            if not 0 <= key < n:
                raise IndexError(
                    f"index {key} is out of bounds for axis 0 with size {n}"
                )
            if isinstance(value, pa.Scalar):
                value = value.as_py()
            elif is_list_like(value):
                raise ValueError("Length of indexer and values mismatch")
            chunks = [
                *self._pa_array[:key].chunks,
                pa.array([value], type=self._pa_array.type, from_pandas=is_nan_na()),
                *self._pa_array[key + 1 :].chunks,
            ]
            data = pa.chunked_array(chunks).combine_chunks()

        elif is_bool_dtype(key):
            key = np.asarray(key, dtype=np.bool_)
            data = self._replace_with_mask(self._pa_array, key, value)

        elif is_scalar(value) or isinstance(value, pa.Scalar):

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Validate `0 <= k < len(arr)` (or `-len(arr) <= k < 0`) before assignment.
  2. Recompute the index from the current array.
  3. Use `.iloc` on the wrapping Series with bounds-checked positions.

Example fix

// before
arr = pd.array([1, 2, 3], dtype="int64[pyarrow]")
arr[5] = 99

// after
arr = pd.array([1, 2, 3, 0, 0, 0], dtype="int64[pyarrow]")
arr[5] = 99
Defensive patterns

Strategy: validation

Validate before calling

def check_index(arr, k):
    n = len(arr)
    kk = k + n if k < 0 else k
    if not 0 <= kk < n:
        raise IndexError(f"index {k} out of bounds for size {n}")
    return kk

Type guard

def index_in_bounds(arr, k) -> bool:
    n = len(arr)
    kk = k + n if k < 0 else k
    return 0 <= kk < n

Try / catch

try:
    arr[k] = v
except IndexError as e:
    if "out of bounds for axis 0" in str(e):
        # extend array or skip
        pass
    else:
        raise

Prevention

When it happens

Trigger: Doing `arr[k] = v` where `k` is an int with `abs(k) >= len(arr)` (or `k < -len(arr)`).

Common situations: Indexing errors after filtering changes length, using DataFrame row numbers on a Series subset, or stale index variables.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/5b4a9cfd006f6ae8. Report an issue: GitHub.