Sub topic 3
Shape, ndim, and size
This chapter assumes you can run Python scripts, know what a NumPy ndarray is, and can create arrays with np.array, np.zeros, and np.arange. Here you will learn the three attributes that describe an array's geometry: shape, ndim, and size. You will also learn how they relate to each other and which mistakes they help you catch.
The three attributes
An ndarray is a block of homogeneous data plus metadata that says how to interpret it as an n-dimensional grid. Three attributes describe that grid.
shapeis a tuple of integers. Entryiis the length of axisi.ndimis the number of axes. It always equalslen(shape).sizeis the total number of elements. It always equals the product of the entries inshape.
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 systemsThis array has 2 rows (axis 0) and 3 columns (axis 1). So shape is (2, 3), ndim is 2, and size is 2 × 3 = 6.
Two further facts are useful:
len(a)returns only the length of axis 0, which isshape[0]. Foraabove it is 2, not 6. Usea.sizefor the element count.shapeis a property of the array object, not a method. Writea.shape, nota.shape().
Reading a shape
Read a shape from the left. The first number is the outermost axis, the one that you index first. For shape == (2, 3), a[0] is a 1-D array of length 3, and there are 2 of them.
The table below shows how ndim and shape relate for common arrays.
| Array | `shape` | `ndim` | `size` |
|---|---|---|---|
| `np.array(7)` | `()` | 0 | 1 |
| `np.array([1, 2, 3])` | `(3,)` | 1 | 3 |
| `np.zeros((2, 3))` | `(2, 3)` | 2 | 6 |
| `np.zeros((4, 2, 3))` | `(4, 2, 3)` | 3 | 24 |
| `np.zeros((0, 3))` | `(0, 3)` | 2 | 0 |
Three rows deserve a closer look.
Zero-dimensional arrays
A 0-D array holds a single value and has an empty shape (). The product of an empty tuple is 1, which is why size is 1. You get a 0-D array from np.array(7). Indexing a 1-D array returns a NumPy scalar, such as np.int64, not a 0-D array. NumPy scalars also have shape (always ()) and ndim (always 0), so you can treat them uniformly.
The one-element tuple
A 1-D array has a shape like (3,). The trailing comma is Python syntax for a tuple with one entry. When you pass a shape to a function, np.zeros(3) and np.zeros((3,)) are equivalent, but np.zeros(3, 2) is an error, because the second positional argument is the dtype. Always wrap multi-axis shapes in a tuple: np.zeros((3, 2)).
Empty arrays
An axis of length 0 gives size == 0. Such arrays are valid and common. For instance, filtering with a boolean mask that matches nothing returns one. They are a frequent source of surprises, because reductions such as max raise an error on them, while sum returns 0.
Shape is not the same as dimensionality in the math sense
NumPy's ndim counts axes, not the mathematical dimension of a vector. A vector with 3 components is a 1-D array with shape == (3,). A 2-D array can also hold the same numbers, but with an explicit row or column axis.
import numpy as np
v = np.array([1, 2, 3])
row = v.reshape(1, 3)
col = v.reshape(3, 1)
for name, arr in [("v", v), ("row", row), ("col", col)]:
print(name, arr.shape, arr.ndim, arr.size)
# v (3,) 1 3
# row (1, 3) 2 3
# col (3, 1) 2 3All three hold the same three numbers, so size is 3 each time. But the shapes differ, and shapes decide how arrays combine in later chapters, particularly under broadcasting. A 1-D array is neither a row nor a column. This is the most common source of shape confusion for people coming from MATLAB.
Inspecting shapes while you work
Checking shape is the fastest debugging tool in NumPy. Most errors you will see are shape mismatches, and the message names the shapes involved.
import numpy as np
a = np.ones((2, 3))
b = np.ones((3, 2))
try:
a + b
except ValueError as e:
print(e)
# operands could not be broadcast together with shapes (2,3) (3,2)Print x.shape at the points where you expect a certain geometry. For quick sanity checks in your own functions, use an assert:
import numpy as np
def center_columns(m):
assert m.ndim == 2, f"expected 2-D array, got ndim={m.ndim}"
return m - m.mean(axis=0)
data = np.array([[1.0, 2.0], [3.0, 6.0]])
print(center_columns(data))
# [[-1. -2.]
# [ 1. 2.]]Shape and size in relation to reshaping
size is the quantity that stays fixed when you reshape. Any new shape must have the same product as the old one. You can use -1 for one axis, and NumPy infers its length from size.
import numpy as np
a = np.arange(12)
print(a.reshape(3, 4).shape) # (3, 4)
print(a.reshape(2, -1).shape) # (2, 6)
print(a.reshape(-1, 1).shape) # (12, 1)
try:
a.reshape(5, -1)
except ValueError as e:
print(e)
# cannot reshape array of size 12 into shape (5,newaxis)The last call fails because 12 is not divisible by 5. Reshaping gets its own chapter. For now, remember the rule: size is preserved, and shape is how that fixed number of elements is laid out.
Changing shape in place
Assigning to a.shape changes the shape of the array in place, again keeping size fixed.
import numpy as np
a = np.arange(6)
a.shape = (2, 3)
print(a)
# [[0 1 2]
# [3 4 5]]This works, but it raises an error if NumPy would need to copy the data. Recent NumPy versions also discourage setting shape directly. Prefer a.reshape(...), which returns a new array object that, when possible, shares the same data.
How the pieces relate
The diagram shows how the three attributes derive from one another.
The last node gives a practical use of ndim. To reach a single element, you need one index per axis. With ndim == 2, a[1, 2] returns an element. With only a[1], you get a whole row, which is an array with ndim == 1.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a[1, 2]) # 6
print(a[1]) # [4 5 6]
print(a[1].shape) # (3,)Common errors
- Confusing
lenandsize.len(a)isa.shape[0]. For a 2-D array it undercounts the elements. It also raisesTypeErrorfor 0-D arrays. - Treating
(n,)as a column. A 1-D array has no row or column orientation. Usereshape(-1, 1)ora[:, np.newaxis]when you need an explicit column. - Passing a bare number list as a shape.
np.zeros([2, 3])works because lists are accepted, butnp.zeros(2, 3)does not. Use a tuple. - Assuming
shapeis a list. It is a tuple, so you cannot assign into it:a.shape[0] = 5raisesTypeError. - Forgetting the empty case. Code that calls
.max()or indexesa[0]fails whensize == 0. Checka.sizefirst when the input may be empty.
Exercises
Exercise
An array has shape (4, 5, 2). What are its ndim and size, and what is the shape of a[0]?
Show answer
ndim is 3 (the length of the shape tuple), size is 4 5 2 = 40, and a[0] has shape (5, 2) because indexing the first axis removes it.
Exercise
You have x = np.arange(8) and want an array with 2 rows and as many columns as needed. What call do you write, and what shape results? Why does x.reshape(3, -1) fail?
Show answer
x.reshape(2, -1) gives shape (2, 4). x.reshape(3, -1) fails because size is 8, and 8 is not divisible by 3, so NumPy cannot infer an integer length for the second axis.
Exercise
For v = np.array([1, 2, 3]), what are v.shape, v.reshape(-1, 1).shape, and v.reshape(1, -1).shape? Which of them has ndim equal to 1?
Show answer
They are (3,), (3, 1), and (1, 3). Only v itself, with shape (3,), has ndim equal to 1. The other two have ndim equal to 2, and all three have size 3.