python type_error ai_generated true

numpy.exceptions.AxisError: axis 2 is out of bounds for array of dimension 2

ID: python/numpy-axis-out-of-bounds

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-04First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Passing an axis argument larger than array.ndim - 1 to functions like np.sum, np.mean, np.concatenate. Often from assuming 3-D input.

generic

中文

向 np.sum、np.mean、np.concatenate 等函数传入大于 array.ndim - 1 的 axis 参数。常因假设输入为 3 维。

Workarounds

  1. 95% success
    np.sum(arr, axis=-1)  # last axis regardless of ndim
  2. 85% success
    assert arr.ndim >= 3 or use np.sum(arr, axis=tuple(range(arr.ndim)))

Dead Ends

Common approaches that don't work:

  1. 95% fail

    Same AxisError

  2. 75% fail

    Changes semantics, not what you want