Sub topic 1
The ndarray: shape, ndim and dtype
Prerequisites
This chapter assumes you know basic Python (lists, loops, functions) and can import and use a third-party library. It also assumes you have a basic idea of what vectors and matrices are. You need NumPy installed, and every example imports it as np.
What an ndarray is
The ndarray is NumPy's core object. It is a fixed-size grid of values that all share one type. Python lists can mix types and grow freely. An ndarray gives up that flexibility and gets compact storage and fast operations in return.
Three attributes describe any array:
| Attribute | Meaning | Example for a 3x4 array of integers |
|---|---|---|
| `shape` | A tuple with the length of each axis | `(3, 4)` |
| `ndim` | The number of axes, which equals `len(shape)` | `2` |
| `dtype` | The type of every element | `int64` on most Linux and macOS systems |
An axis is one dimension of the array. A 2-D array has axis 0 (the rows) and axis 1 (the columns).
Inspecting an array
The example below creates a 3x4 array and reads its attributes. It also selects data with basic indexing, which later chapters cover in full.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a.shape) # (3, 4)
print(a.ndim) # 2
print(a[1, 2]) # 6
print(a[:, 1]) # [1 5 9]np.arange(12) produces the integers 0 to 11 in one axis. reshape(3, 4) arranges the same 12 values into 3 rows of 4. The index a[1, 2] means row 1, column 2, which holds 6. The index a[:, 1] means all rows of column 1.
The shape tuple always multiplies out to the total element count, which is available as a.size. Here that is 3 × 4 = 12.
The diagram below shows how the attributes relate to one array.
Shape versus ndim
People often confuse the two. ndim counts axes. shape gives the length of each one. These three arrays hold similar data but have different structure:
import numpy as np
v = np.array([1, 2, 3]) # shape (3,)
r = np.array([[1, 2, 3]]) # shape (1, 3)
c = np.array([[1], [2], [3]]) # shape (3, 1)
for name, arr in [("v", v), ("r", r), ("c", c)]:
print(name, arr.shape, arr.ndim)This prints v (3,) 1, r (1, 3) 2 and c (3, 1) 2. A 1-D array of shape (3,) is neither a row nor a column. This distinction matters a great deal when you reach broadcasting, so it is worth learning now.
A shape with one element needs a trailing comma, as in (3,). Without the comma, Python reads (3) as the plain integer 3.
The dtype
The dtype fixes how each element is stored and how much memory it takes. Common ones are int64, float64, bool and float32. NumPy picks a dtype when you build the array, based on the values you give it.
import numpy as np
ints = np.array([1, 2, 3])
floats = np.array([1, 2.5, 3])
small = np.array([1, 2, 3], dtype=np.float32)
print(ints.dtype) # int64 (platform dependent)
print(floats.dtype) # float64
print(small.dtype) # float32
print(small.itemsize, small.nbytes) # 4 12Mixing an integer and a float makes the whole array float64, because one dtype must fit every element. itemsize is the bytes per element and nbytes is the total bytes for the data.
Use astype to convert. It returns a new array and leaves the original unchanged:
import numpy as np
x = np.array([1.9, 2.1, -0.5])
print(x.astype(int)) # [ 1 2 0]Converting a float to an integer truncates toward zero. It does not round.
Common errors
- Reading
shapeas a list of values. It is a tuple of axis lengths. - Expecting
(3,)to behave like a row or a column. It has one axis only. - Forgetting that a dtype applies to the whole array, so one float turns a list of integers into floats.
- Assuming
astype(int)rounds.
Exercise
What are the shape, ndim and dtype of np.array([[1, 2], [3, 4], [5, 6.5]])?
Show answer
The shape is (3, 2) and ndim is 2. The dtype is float64, because the single float 6.5 forces every element to be stored as a float.
Exercise
An array has shape (2, 5, 3). What are its ndim and size?
Show answer
ndim is 3, because the shape has three entries. The size is 2 × 5 × 3 = 30 elements.