NumPy Array Shape
The shape of a NumPy array tells you exactly how many elements exist along every dimension.
Shape of an Array
Shape is one of the most useful attributes on an ndarray. It describes the size of the array along each dimension as a tuple, and the number of items in that tuple equals the number of dimensions, or axes, the array has.
Example
import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)
# Output:
# (2, 4)The tuple (2, 4) means this array has 2 elements along the first axis (2 rows) and 4 elements along the second axis (4 columns). Each number in the tuple corresponds to one dimension, read from the outermost axis to the innermost.
Shape With Higher Dimensions
Example
import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array :', arr.shape)
# Output:
# [[[[[1 2 3 4]]]]]
# shape of array : (1, 1, 1, 1, 4)Here ndmin=5 forces NumPy to wrap the data in enough extra dimensions to reach 5 axes total. Reading the tuple from left to right, the first four axes each hold a single nested array, and the fifth and final axis holds the four actual values.
- shape[0] is the size of the outermost axis (often the number of rows or top-level groups).
- The last value in the shape tuple is the size of the innermost axis (often the number of columns).
- len(arr.shape) always equals arr.ndim, the number of dimensions.
- A 1-D array's shape is a one-item tuple like (4,), not the bare number 4.
Example
import numpy as np
arr1d = np.array([1, 2, 3, 4, 5])
arr2d = np.array([[1, 2, 3], [4, 5, 6]])
arr3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr1d.shape, arr1d.ndim)
print(arr2d.shape, arr2d.ndim)
print(arr3d.shape, arr3d.ndim)
# Output:
# (5,) 1
# (2, 3) 2
# (2, 2, 2) 3Exercise: NumPy Array Shape
What does the .shape attribute of a NumPy array return?