๐Ÿ€Zerve chosen as NCAA's Agentic Data Platform for 2026 Hackathonยท๐ŸงฎMeet the Zerve Team at Data Decoded Londonยท๐Ÿ“ˆWe're hiring โ€” awesome new roles just gone live!
Back
Numpy

AxisError: Axis is Out of Bounds for Array - How to Fix It

Answer

This error means you're specifying an axis that doesn't exist for your array's dimensions. A 1D array only has axis 0, a 2D array has axes 0 and 1. Fix it by checking your array's number of dimensions with .ndim and using a valid axis value.

Why This Happens

The axis parameter tells NumPy which dimension to operate along. If you have a 1D array and specify axis=1, NumPy fails because there is no second dimension. This commonly happens when you assume an array is 2D when it's actually 1D, or when copying code that worked on differently-shaped data.

Solution

The rule: always check .ndim or .shape before using the axis parameter. Use axis=-1 for the last dimension when you don't know the exact number of dimensions.

import numpy as np

arr_1d = np.array([1, 2, 3, 4, 5])

# โŒ Problematic: 1D array has no axis 1
np.sum(arr_1d, axis=1)
# AxisError: axis 1 is out of bounds for array of dimension 1

# โœ… Fixed: use axis 0 for 1D arrays
np.sum(arr_1d, axis=0)  # returns 15

# โœ… Fixed: or just omit axis for total sum
np.sum(arr_1d)  # returns 15

# โœ… Debug: check array dimensions first
print(arr_1d.ndim)   # 1
print(arr_1d.shape)  # (5,)

# โŒ Problematic: assuming 2D when actually 1D
data = np.array([1, 2, 3])  # 1D
np.mean(data, axis=1)  # fails

# โœ… Fixed: reshape to 2D if you need axis 1
data_2d = data.reshape(1, -1)  # shape (1, 3)
np.mean(data_2d, axis=1)  # works

# โœ… Fixed: expand dimensions
data_2d = np.expand_dims(data, axis=0)
np.mean(data_2d, axis=1)

# โœ… Valid axes for different dimensions
# 1D array: axis 0 only (or -1)
# 2D array: axis 0 (rows) or 1 (columns)
# 3D array: axis 0, 1, or 2

# โœ… Use negative indexing for last axis
arr_2d = np.array([[1, 2], [3, 4]])
np.sum(arr_2d, axis=-1)  # same as axis=1, sums along last axis

Better Workflow

In Zerve, every block automatically displays variable shapes, types, and dimensions. No need to manually add print statements. Run error demonstrations and solutions side by side, see exactly where dimensional mismatches occur. All block outputs remain visible on the canvas, so you can compare error states with fixed states instantly. Identify and fix dimensional errors in seconds rather than minutes.

Better workflow

Related Topics

Decision-grade data work

Explore, analyze and deploy your first project in minutes