Sub topic 3
Shape, ndim, and size
This chapter assumes you can create an array with np.array and have a rough idea of what a matrix is. Here you will learn the three attributes that describe an array's layout, and the shape mistakes that cause most early NumPy errors.
The three attributes
Every ndarray reports its layout through three attributes:
shapeis a tuple with one length per axis.ndimis the number of axes.sizeis the total number of elements.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape) # (2, 3)
print(a.ndim) # 2
print(a.size) # 6
print(a.dtype) # int64 on most 64-bit Linux and macOS systemsThe shape (2, 3) means 2 along axis 0 (the rows) and 3 along axis 1 (the columns). The other two attributes follow from it. ndim equals len(a.shape), and size is the product of the entries in shape.
Higher dimensions
The same rules apply to any number of axes. The shape tuple lists axes from outermost to innermost.
import numpy as np
b = np.zeros((2, 3, 4))
print(b.shape) # (2, 3, 4)
print(b.ndim) # 3
print(b.size) # 24
print(len(b)) # 2, the length of axis 0 onlylen() returns only the length of the first axis. Use size when you want the total element count.
One-dimensional shapes
A 1-D array has a one-element shape tuple. That tuple needs a trailing comma, because (3) is just the integer 3 in Python.
import numpy as np
v = np.array([10, 20, 30])
col = v.reshape(3, 1)
row = v.reshape(1, 3)
print(v.shape, v.ndim) # (3,) 1
print(col.shape, col.ndim) # (3, 1) 2
print(row.shape, row.ndim) # (1, 3) 2These three arrays hold the same three numbers, but NumPy treats them as different objects. Shape (3,) is neither a row nor a column. Shapes (3, 1) and (1, 3) are 2-D, and they behave differently when combined with other arrays. The broadcasting chapter covers that in detail. Reshaping gets its own chapter, but the call above is enough to see the effect.
Common errors
- Reading the shape as
(columns, rows). The order is rows first. A 2-by-3 array has shape(2, 3). - Ragged input. Nested lists of unequal length do not form a regular grid. Recent NumPy versions raise a
ValueErrorfornp.array([[1, 2], [3]])unless you passdtype=object. - Using
len()as the element count. It gives the size of axis 0 only. - Assigning to
shape. Settinga.shape = (3, 2)works in place, butreshapeis clearer and safer.
Summary
| Attribute | Meaning | For `np.zeros((2, 3, 4))` |
|---|---|---|
| `shape` | Length of each axis | `(2, 3, 4)` |
| `ndim` | Number of axes | `3` |
| `size` | Total element count | `24` |
Exercise
An array x has shape (4, 5, 2). What are x.ndim, x.size, and len(x)? Then explain why np.array([1, 2, 3]) is not the same as an array of shape (3, 1).
Show answer
x.ndim is 3, x.size is 4 5 2 = 40, and len(x) is 4, the length of axis 0. The array np.array([1, 2, 3]) has shape (3,) and one axis, while shape (3, 1) has two axes. Because the number of axes differs, the two shapes behave differently in operations such as broadcasting.