ndim is simply the length of the array's shape tuple: a 1D array, a plain vector, has ndim 1, a 2D array, a matrix of rows and columns, has ndim 2, and higher-dimensional arrays, common in image or video data (height, width, color channels, and sometimes a batch dimension), have correspondingly higher ndim values. A 0-dimensional array, holding just a single scalar value wrapped in the ndarray type, has ndim 0.
1Understanding ndarray.ndim
ndim is simply the length of the array's shape tuple: a 1D array, a plain vector, has ndim 1, a 2D array, a matrix of rows and columns, has ndim 2, and higher-dimensional arrays, common in image or video data (height, width, color channels, and sometimes a batch dimension), have correspondingly higher ndim values. A 0-dimensional array, holding just a single scalar value wrapped in the ndarray type, has ndim 0.
A common bug source is accidentally ending up with an extra dimension of size 1, a shape like (5, 1) instead of (5,), after some operation — checking .ndim is a quick way to catch this before it causes confusing broadcasting behavior downstream.
import numpy as np
vector = np.array([1, 2, 3])
matrix = np.array([[1, 2], [3, 4]])
print(vector.ndim, matrix.ndim)2Practical Example
Here is a real-world application of ndarray.ndim showing how it is used in production NumPy code.
import numpy as np
image_batch = np.zeros((10, 64, 64, 3))
print(image_batch.ndim)
print(image_batch.shape)3Best Practices
Follow these guidelines when working with ndarray.ndim:
1. Check .ndim when debugging unexpected shapes, especially after operations like slicing or reductions that can add or remove dimensions unexpectedly
2. Use np.squeeze() to remove unwanted size-1 dimensions when .ndim is higher than you actually intend
3. Be explicit with axis arguments in reduction functions instead of relying on default behavior that can silently reduce dimensionality
Tip: A common bug source is accidentally ending up with an extra dimension of size 1, a shape like (5, 1) instead of (5,), after some operation — checking .ndim is a quick way to catch this before it causes confusing broadcasting behavior downstream.
import numpy as np
vector = np.array([1, 2, 3])
matrix = np.array([[1, 2], [3, 4]])
print(vector.ndim, matrix.ndim)