shape (NumPy)

The shape attribute is a tuple giving the size of a NumPy array along each axis. A shape of (2, 3) means a 2-D array with 2 rows and 3 columns; the length of the tuple is the number of dimensions.

NumPy

shape is the first thing you check about an array, because almost every NumPy operation cares about it. A 1-D array has shape (n,), a matrix has shape (rows, cols), and a stack of images might have shape (count, height, width, channels). The product of the shape equals the total element count, .size.

You can reshape an array to a new compatible shape with .reshape, as long as the number of elements stays the same. Assigning a new tuple to .shape changes it in place when the data layout allows it.

Mismatched shapes are the most common source of NumPy errors; broadcasting rules decide whether two differently shaped arrays can combine, and checking shapes is the first step in debugging them.

Syntax

a.shape  |  a.reshape(new_shape)

Examples

Python

import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape)

Output:

(2, 3)

Learn it in a lesson

See also

Back to the Dictionary