NumPy: Arrays for ML Data
After this lesson, you will be able to:
- Read an array's shape and dtype and predict what slicing and reshaping will return
- Replace a Python loop with a vectorised expression and measure the difference with timeit
- Centre a feature matrix by its column means using broadcasting, and check both shapes first
- Select rows with boolean masks and summarise along an axis
- Draw repeatable random numbers with a seeded generator
Before you start
pip install numpy in your virtual environment. In this page's code cells it is already available.#The Problem: A Feature Table in Plain Python
Four users, three numbers each: sessions per week, average minutes per session, and months since signup. This is invented sample data. Subtracting 2 from every number sounds trivial.
rows = [[3, 42.0, 12], [10, 15.5, 30], [1, 8.0, 2], [7, 30.5, 18]]
try:
print(rows - 2)
except TypeError as e:
print("TypeError:", e)
print([1, 2, 3] * 2)Output:
TypeError: unsupported operand type(s) for -: 'list' and 'int'
[1, 2, 3, 1, 2, 3]
- fails, and * does something unrelated (it repeats the list). To subtract, you would write a nested loop and track indexes yourself, and to standardise each column you would write several more.ndarray: a grid of numbers that all share one type, stored in one block of memory, with arithmetic that applies to every element. Import it by convention as np.#Arrays: Shape and dtype
import numpy as np
rows = [[3, 42.0, 12], [10, 15.5, 30], [1, 8.0, 2], [7, 30.5, 18]]
X = np.array(rows)
print(X)
print(X.shape, X.ndim, X.size, X.dtype)
y = np.array([0, 1, 0, 1])
print(y.shape, y.dtype.kind)Output:
[[ 3. 42. 12. ]
[10. 15.5 30. ]
[ 1. 8. 2. ]
[ 7. 30.5 18. ]]
(4, 3) 2 12 float64
(4,) i
(4, 3): 4 rows (users) and 3 columns (features). ndim is 2, size is 12, and the dtype is float64. Notice that you wrote integers and floats, and everything became float. An array has one dtype, so NumPy picks one that fits all entries. The labels y are all integers, so their dtype kind is i (a signed integer). The exact width, int32 or int64, depends on the platform, which is why the code prints the kind.X with shape (n_samples, n_features) and y with shape (n_samples,). A shape with one number in the tuple, like (4,), is a one-dimensional array, not a column.What dtype does np.array([1, 2, 3.5]) have, and what does np.array([1, 'a']) give?
Three ways to create arrays without typing them out, and one to change the shape:
import numpy as np
print(np.zeros((2, 3)))
print(np.arange(6))
flat = np.arange(6)
grid = flat.reshape(2, 3)
print(grid)
print(grid.shape, flat.reshape(3, -1).shape)
print(np.array([1, 2, 3], dtype=np.float32).dtype)Output:
[[0. 0. 0.]
[0. 0. 0.]]
[0 1 2 3 4 5]
[[0 1 2]
[3 4 5]]
(2, 3) (3, 2)
float32
reshape re-reads the same numbers with a new shape. The total count must stay the same, and -1 means "work this length out for me". You can also choose a dtype, which matters when a model expects float32.#Indexing and Slicing
X[row, column]. A colon means "all of this axis".import numpy as np
X = np.array([[3, 42.0, 12], [10, 15.5, 30], [1, 8.0, 2], [7, 30.5, 18]])
print(X[0]) # first user, all features
print(X[0, 1]) # first user, minutes
print(X[:, 1]) # every user, minutes only
print(X[1:3, :2]) # users 1 and 2, first two features
print(X[-1]) # last user
print(X[:, 1].shape, X[:, 1:2].shape)Output:
[ 3. 42. 12.]
42.0
[42. 15.5 8. 30.5]
[[10. 15.5]
[ 1. 8. ]]
[ 7. 30.5 18. ]
(4,) (4, 1)
X[:, 1] has shape (4,). A slice keeps it, so X[:, 1:2] has shape (4, 1). Many functions want the column form, and you will meet that shortly.import numpy as np
a = np.arange(5)
b = a[1:4]
b[0] = 99
print(a)
c = a[1:4].copy()
c[0] = -1
print(a, c)Output:
[ 0 99 2 3 4]
[ 0 99 2 3 4] [-1 2 3]
.copy() when you need an independent array.#Vectorisation Versus a Loop
import timeit
import numpy as np
n = 1_000_000
data = list(range(n))
arr = np.arange(n)
t_loop = timeit.timeit(lambda: [x * 2 + 1 for x in data], number=5) / 5
t_np = timeit.timeit(lambda: arr * 2 + 1, number=5) / 5
print(f"list comprehension: {t_loop * 1000:.1f} ms")
print(f"numpy expression: {t_np * 1000:.2f} ms")
print(f"ratio: {t_loop / t_np:.0f}x")Run it and read your own numbers. They change with the machine and library versions. On one laptop this gave about 27 ms for the list comprehension and about 1 ms for NumPy, a ratio near 30. The gap is real, but it is not a constant, and it shrinks for tiny arrays. The ratio matters less than the habit: when you can say a calculation as one expression on whole arrays, do.
#The axis Argument
sum, mean, max and argmax take an axis. The axis you name is the one that disappears. For a feature matrix that is usually one of two questions.import numpy as np
X = np.array([[3, 42.0, 12], [10, 15.5, 30], [1, 8.0, 2], [7, 30.5, 18]])
print(X.sum(axis=0)) # per feature: collapses the users
print(X.sum(axis=1)) # per user: collapses the features
print(X.sum()) # one number
print(X.max(axis=0), X.argmax(axis=0))
T = np.arange(24).reshape(2, 3, 4)
print(T.sum(axis=0).shape, T.sum(axis=1).shape, T.sum(axis=2).shape)Output:
[21. 96. 62.]
[57. 55.5 11. 55.5]
179.0
[10. 42. 30.] [1 0 1]
(3, 4) (2, 4) (2, 3)
axis=0 runs down the rows and gives one number per column, so for X the result has shape (3,). axis=1 runs across and gives one number per row, shape (4,). On the 3D array the named axis is the one removed from the shape: (2, 3, 4) becomes (3, 4), (2, 4) or (2, 3). If you are unsure, print the result's shape. The same argument works for mean: X.mean(axis=0) is one average per column, which is exactly what the next section needs.#Broadcasting
ValueError.X.mean(axis=0) gives one mean per column. np.allclose(a, b) is True when two arrays are equal up to tiny floating-point rounding, which is how you check a result that should be exactly zero.import numpy as np
X = np.array([[3, 42.0, 12], [10, 15.5, 30], [1, 8.0, 2], [7, 30.5, 18]])
col_mean = X.mean(axis=0)
print(col_mean, col_mean.shape)
centered = X - col_mean
print(centered.round(2))
print(np.allclose(centered.mean(axis=0), 0))Output:
[ 5.25 24. 15.5 ] (3,)
[[ -2.25 18. -3.5 ]
[ 4.75 -8.5 14.5 ]
[ -4.25 -16. -13.5 ]
[ 1.75 6.5 2.5 ]]
True
X is (4, 3) and col_mean is (3,). Aligned from the right, the 3 matches the 3, and the missing leading axis is stretched, so the same vector of means is subtracted from every row. No loop, and no copy of the means. Add a division by X.std(axis=0) and you have standardised each feature to mean 0 and standard deviation 1.import numpy as np
X = np.array([[3, 42.0, 12], [10, 15.5, 30], [1, 8.0, 2], [7, 30.5, 18]])
Z = (X - X.mean(axis=0)) / X.std(axis=0)
print(Z.round(2))
print(np.allclose(Z.mean(axis=0), 0), np.allclose(Z.std(axis=0), 1))
try:
X - np.array([1.0, 2.0])
except ValueError as e:
print("ValueError:", e)Output:
[[-0.64 1.37 -0.35]
[ 1.36 -0.65 1.43]
[-1.22 -1.21 -1.33]
[ 0.5 0.49 0.25]]
True True
ValueError: operands could not be broadcast together with shapes (4,3) (2,)
When the shapes cannot line up, NumPy tells you. The dangerous case is when they line up by accident. Say you want to centre each row (each user) by its own mean instead, on a square 3 by 3 matrix.
G has shape (3, 3) and rm = G.mean(axis=1) has shape (3,). What does G - rm do?
import numpy as np
G = np.array([[1., 2., 3.], [4., 5., 6.], [7., 8., 9.]])
rm = G.mean(axis=1)
print(G - rm) # wrong: rows are not centred
print(G - G.mean(axis=1, keepdims=True)) # right: shape (3, 1)
print(G.mean(axis=1, keepdims=True).shape)Output:
[[-1. -3. -5.]
[ 2. 0. -2.]
[ 5. 3. 1.]]
[[-1. 0. 1.]
[-1. 0. 1.]
[-1. 0. 1.]]
(3, 1)
keepdims=True.#Boolean Masks
True and False of the same shape. That is a mask, and indexing with it keeps only the True entries.import numpy as np
X = np.array([[3, 42.0, 12], [10, 15.5, 30], [1, 8.0, 2], [7, 30.5, 18]])
y = np.array([0, 1, 0, 1])
print(X[:, 0] > 2)
print(X[X[:, 0] > 2])
print(X[y == 1])
mask = (X[:, 0] > 2) & (X[:, 1] < 40)
print(mask, X[mask].shape)
print(y.mean(), (y == 1).sum())Output:
[ True True False True]
[[ 3. 42. 12. ]
[10. 15.5 30. ]
[ 7. 30.5 18. ]]
[[10. 15.5 30. ]
[ 7. 30.5 18. ]]
[False True False True] (2, 3)
0.5 2
X[y == 1] selects the rows whose label is 1, which is how you split a dataset by class. Combine masks with & (and), | (or) and ~ (not), and wrap each comparison in parentheses. Because True counts as 1, .sum() counts matches and .mean() gives the fraction.This should print the rows where sessions is above 2 and minutes is below 40. It raises an error instead. Fix the condition.
[[10. 15.5 30. ] [ 7. 30.5 18. ]]
#Random Numbers and Seeds
Training and tests that use random data give different results on every run unless you fix the starting state. Create one generator with a seed and draw everything from it.
import numpy as np
rng = np.random.default_rng(42)
print(rng.normal(size=3))
rng = np.random.default_rng(42)
print(rng.normal(size=3))Output:
[ 0.30471708 -1.03998411 0.7504512 ]
[ 0.30471708 -1.03998411 0.7504512 ]
The two draws match because both generators started from seed 42. Seeding makes a run repeatable on the same library version, but not identical across versions.
#Shapes in ML Code
reshape(32, -1):import numpy as np
batch = np.zeros((32, 28, 28)) # 32 grayscale images
print(batch.shape, batch[0].shape)
print(batch.reshape(32, -1).shape) # flatten each image to a vectorOutput:
(32, 28, 28) (28, 28)
(32, 784)
32 is the batch (the number of images) and 28 x 28 is one image, which flattens to 784 numbers. Check what layout the layer or function you call expects before you reshape. The neural-network tracks come back to image shapes in detail.Interactive Lab
Interactive view of how vectors and matrices combine, the math behind array operations
#Common Mistakes
Mixing types in one array
A text value turns the whole array into text, and arithmetic fails later.
import numpy as np
a = np.array([1, 2, "3"])
print(a.dtype.kind) # U means text
try:
a + 1
except TypeError as e:
print("TypeError caught")
b = np.array([1, 2, "3"]).astype(float)
print(b + 1)Output:
U
TypeError caught
[2. 3. 4.]
astype at the boundary, and check dtype after loading data.Assuming a slice is a copy
b = a[1:4] writes to a. Use .copy() when you plan to change the slice, as shown earlier.Using and instead of &
and, or and not ask for one True or False. Masks are arrays of them. Use &, | and ~, with parentheses around each comparison.Letting one NaN spoil a result
NaN means "not a number", a float marker for a missing value. In a NumPy array it spreads: any sum or mean that includes it is nan. The nan-prefixed functions skip it.import numpy as np
a = np.array([4.0, np.nan, 8.0])
print(a.mean(), np.nanmean(a))
print(np.isnan(a))
print(np.nan == np.nan)Output:
nan 6.0
[False True False]
False
NaN is not equal to anything, itself included, so a == np.nan is never true. Find gaps with np.isnan. The next lesson shows how pandas treats the same gaps, and why skipping them silently is a choice you should make on purpose.#Try It
Six invented users, three features each, and a label that says whether the user later left. In the starter, fill in three steps: standardise the features with broadcasting, compare the average feature values of the two label groups with masks, and split the rows into a train part and a test part with a seeded generator.
Tests: Expected output: (6, 3) True, then [ 9.7 33.7 29.3] [ 3. 23.7 7.7], then [3 2 5 4 0 1], then (4, 3) (2, 3) [1 0 1 0]
X.mean(axis=0).shape first and check it against the last axis of X. For step 2, X[y == 1] keeps the rows with label 1, and the mean down those rows is axis=0. For step 3, rng.permutation(6) returns the numbers 0 to 5 in random order, and X[idx[:4]] picks those rows.#Going Further
X and y you made here. Pandas Advanced then covers joins, pivots and time series, and the plotting lesson draws arrays and tables. For how arrays feed models, the Python for ML lesson builds on exactly this X and y. NumPy also has np.sort and np.argsort, which sort in compiled code, and np.where(condition, a, b), a vectorised if-else.#Key Takeaways
Key takeaways
- An array has a shape and one dtype. Read both first, and expect a table of examples to be (n_samples, n_features).
- An integer index removes an axis and a slice keeps it. Slices are views that share memory, so copy before you change one.
- Vectorised expressions replace loops. Measure with timeit on your own machine rather than trusting a quoted ratio.
- Broadcasting compares shapes from the last axis. Subtracting X.mean(axis=0) from X centres each column, and keepdims=True keeps a reduced axis for broadcasting back.
- Masks select with &, | and ~, never and, or, not. Sum and mean of a mask count and average matches.
- A seeded default_rng makes random draws repeatable, and a NaN spoils a plain mean unless you use the nan functions.
`X` has shape (4, 3). What is the shape of `X[:, 1:2]`?