Sub topic 1
The ndarray: shape, ndim and dtype
Prerequisites
This chapter assumes the following:
- You can write basic Python: lists, loops and functions.
- You can import and call a third-party library.
- You know what a vector (a list of numbers) and a matrix (a table of numbers) are.
You don't need to know NumPy yet. Every later chapter in this tutorial builds on the three attributes covered here: shape, ndim and dtype. Most NumPy errors come from misreading one of them.
What an ndarray is
The ndarray is NumPy's core object. It is an N-dimensional array: a block of values laid out in memory, all of the same type, with metadata that says how to read that block.
A Python list can hold mixed types, and each item is a separate object with its own overhead. An ndarray stores raw values side by side, which is why NumPy can run operations in compiled code instead of a Python loop. The cost is a restriction: every element has the same type, and the array has a fixed size once created.
Three attributes describe an array:
| Attribute | Meaning | Example for a 3x4 array of 64-bit integers |
|---|---|---|
| `shape` | Tuple with the length of each axis | `(3, 4)` |
| `ndim` | Number of axes, equal to `len(shape)` | `2` |
| `dtype` | Type shared by every element | `int64` |
Two derived attributes are also useful: size is the total number of elements (the product of the shape), and nbytes is the memory the elements occupy.
Shape and ndim
Create a small array and inspect it.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a.shape) # (3, 4)
print(a.ndim) # 2
print(a.size) # 12
print(a[1, 2]) # 6
print(a[:, 1]) # [1 5 9]np.arange(12) produces the integers 0 to 11. reshape(3, 4) reinterprets those 12 values as 3 rows of 4 columns. The shape (3, 4) reads as "axis 0 has length 3, axis 1 has length 4". Axis 0 runs down the rows and axis 1 runs across the columns. The next chapters on indexing and reductions rely on this numbering.
The element at row 1, column 2 is a[1, 2], which is 6. The slice a[:, 1] means "every row, column 1". Later chapters cover indexing in full. Here it only shows that the shape tells you how many indices an element needs.
Dimensions of different sizes
The number of axes is not the same as the number of elements or the length of a vector. These four arrays have different ndim values:
import numpy as np
s = np.array(5) # scalar
v = np.array([1, 2, 3]) # vector
m = np.array([[1, 2, 3]]) # matrix with one row
t = np.zeros((2, 3, 4)) # three axes
for name, x in [("s", s), ("v", v), ("m", m), ("t", t)]:
print(name, x.shape, x.ndim, x.size)
# s () 0 1
# v (3,) 1 3
# m (1, 3) 2 3
# t (2, 3, 4) 3 24Note these points:
- A zero-dimensional array has the empty shape
(). It holds exactly one value. - A one-element tuple must be written with a trailing comma:
(3,). Without the comma,(3)is just the integer 3. vwith shape(3,)andmwith shape(1, 3)hold the same numbers. NumPy treats them as different objects. A one-dimensional array is neither a row nor a column. This difference decides how arrays line up in broadcasting, which later chapters explain.
The shape tuple as an argument
Functions that create arrays take the shape as one tuple. np.zeros((3, 4)) is correct. np.zeros(3, 4) fails, because the second positional argument is the dtype and 4 is not a valid dtype. The error message mentions that 4 cannot be interpreted as a data type, which can be confusing the first time you see it.
The dtype
A dtype (data type) says how many bytes each element uses and how to interpret them: signed integer, unsigned integer, floating point, boolean, and so on.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a.dtype) # int64 on most Linux and macOS systems
print(a.itemsize) # 8 bytes per element
print(a.nbytes) # 96 = 12 elements * 8 bytes
print(a.strides) # (32, 8)The default integer type depends on the platform. On most 64-bit Linux and macOS systems it is int64. On Windows with NumPy 1.x it is int32. If your output differs from this tutorial's, check the dtype first.
The strides attribute gives the number of bytes to step in memory to move one position along each axis. Here one step along axis 1 moves 8 bytes (one element) and one step along axis 0 moves 32 bytes (a whole row of four elements). You rarely need strides in daily work. They explain why transposing is cheap: a.T has shape (4, 3) and strides (8, 32), and it reuses the same memory.
Common dtypes
| dtype | Meaning | Typical use |
|---|---|---|
| `int32`, `int64` | Signed integers | Counts, indices |
| `uint8` | Unsigned 8-bit integer, 0 to 255 | Image pixels |
| `float32`, `float64` | Floating point | Measurements, most numerical work |
| `bool` | True or False | Masks and comparisons |
float64 is the default for decimal numbers. float32 uses half the memory and is common in machine learning, with fewer digits of precision.
How NumPy picks a dtype
When you build an array from a Python list, NumPy chooses the smallest common type that holds every element:
import numpy as np
print(np.array([1, 2, 3]).dtype) # int64
print(np.array([1, 2.5]).dtype) # float64
print(np.array([True, False]).dtype) # bool
print(np.array([1, 2, 3], dtype=np.float32).dtype) # float32The second line shows upcasting: one float in the list makes the whole array float64. You can override the choice with the dtype argument. Convert an existing array with astype, which returns a new array:
import numpy as np
a = np.arange(5)
f = a.astype(np.float32)
print(f.dtype) # float32
print(a.dtype) # int64, the original is unchangedOperations also pick a dtype
Combining arrays of different types produces the wider type. Dividing integers with / always produces floats:
import numpy as np
n = np.array([1, 2, 3])
print(n / 2) # [0.5 1. 1.5]
print((n / 2).dtype) # float64Gotchas with dtype
The fixed dtype causes behavior that surprises people coming from Python lists.
- Assignment converts to the array's dtype. Assigning a float into an integer array truncates it without a warning.
- Integer overflow wraps around. Fixed-width integers cannot grow, so a result that does not fit is reduced modulo the type's range.
- Strings in a numeric array fail or change the dtype. Assigning
"x"into an integer array raises aValueError, while building an array from mixed numbers and strings makes the whole array a string type.
import numpy as np
b = np.arange(5)
b[0] = 2.7
print(b) # [2 1 2 3 4], 2.7 became 2
x = np.array([200], dtype=np.uint8)
y = np.array([100], dtype=np.uint8)
print(x + y) # [44], 300 wrapped around modulo 256Checking shapes in practice
A habit worth building is to write the expected shape next to each line while you work. This matches how the rest of the tutorial presents code.
import numpy as np
data = np.arange(6, dtype=np.float64).reshape(2, 3)
print(data.shape) # (2, 3)
print(data.T.shape) # (3, 2)
print(data.reshape(-1).shape) # (6,)
print(len(data)) # 2, len() gives the length of axis 0 onlyTwo details appear here. len(data) returns only the length of axis 0, not the total number of elements, so use size for that. In reshape, the value -1 means "work out this length from the others". The next chapters return to both ideas.
Exercises
Exercise
For t = np.zeros((2, 3, 4)), what are t.shape, t.ndim, t.size and t.nbytes? Assume the default dtype is float64.
Show answer
t.shape is (2, 3, 4), t.ndim is 3, t.size is 24 (2 3 4), and t.nbytes is 192, because a float64 element takes 8 bytes and 24 * 8 = 192.
Exercise
You run c = np.array([10, 20, 30]); c[1] = 7.9; print(c). What does it print, and why?
Show answer
It prints [10 7 30]. The array has an integer dtype, so the assigned float 7.9 is converted to an integer by truncation, with no warning.
Exercise
Do np.array([1, 2, 3]) and np.array([[1, 2, 3]]) have the same shape? Give both shapes and both ndim values.
Show answer
No. The first has shape (3,) and ndim 1. The second has shape (1, 3) and ndim 2. They hold the same numbers, but they are different arrays and will behave differently when combined with other arrays.