Edexcel International Advanced Level Computer Science, point 18.1.3
NumPy is a third-party library for fast numerical work with arrays. It is installed separately (pip install numpy), and imported by convention as np. Check the Programming Language Subset (PLS) for the functions allowed.
import numpy as np
Why NumPy?
- A NumPy array holds items of one type in a compact block of memory, so it is much faster and uses less memory than a Python list for large amounts of numbers.
- Operations apply to the whole array at once (vectorisation), with no loops to write.
- It suits data science and scientific computing (6.1.2).
a. Array
Creating arrays
a = np.array([3, 1, 4, 1, 5]) # from a list
# [3 1 4 1 5] int64 (int32 on some systems)
print(a, a.dtype)
b = np.array([[1, 2, 3],
# a 2D array from a list of lists
[4, 5, 6]])
print(np.zeros(4)) # [0. 0. 0. 0.]
print(np.ones((2, 3))) # 2 rows, 3 columns of 1.0
print(np.arange(0, 10, 2)) # [0 2 4 6 8]
print(np.linspace(0, 1, 5)) # [0. 0.25 0.5 0.75 1. ]
print(np.full(3, 7)) # [7 7 7]
dtypeis the array's data type (int64,float64,bool).- All elements have the same type: mixing ints and floats makes all floats.
Indexing and slicing
a = np.array([10, 20, 30, 40, 50])
print(a[1], a[-1]) # 20 50
print(a[1:4]) # [20 30 40]
b = np.array([[1, 2, 3], [4, 5, 6]])
print(b[1, 2]) # 6 (row 1, column 2)
print(b[0]) # [1 2 3] (a row)
print(b[:, 1]) # [2 5] (a column)
print(a[a > 25]) # [30 40 50] (boolean mask)
b. Arithmetic
Operators work element by element:
x = np.array([1, 2, 3])
y = np.array([10, 20, 30])
print(x + y) # [11 22 33]
print(y - x) # [ 9 18 27]
# [10 40 90] (NOT a dot product)
print(x * y)
print(y / x) # [10. 10. 10.]
print(x ** 2) # [1 4 9]
# [10 20 30] (a scalar is "broadcast")
print(x * 10)
print(x > 1) # [False True True]
Broadcasting: a single value (or a smaller array) is stretched to fit the bigger one.
Summary functions:
data = np.array([4, 8, 15, 16, 23, 42])
print(data.sum(), data.mean(), data.max(), data.min()) # 108 18.0 42 4
print(np.median(data), data.std().round(2)) # 15.5 12.32
print(np.sqrt(np.array([4, 9, 16]))) # [2. 3. 4.]
print(np.dot(x, y)) # 140
Along rows or columns of a 2D array:
m = np.array([[1, 2, 3],
[4, 5, 6]])
# [5 7 9] (down each column)
print(m.sum(axis=0))
# [ 6 15] (across each row)
print(m.sum(axis=1))
print(m.mean(axis=1)) # [2. 5.]
c. Rounding
v = np.array([1.234, 5.678, 9.1011])
print(np.round(v, 2)) # [1.23 5.68 9.1 ]
print(np.floor(v)) # [1. 5. 9.]
print(np.ceil(v)) # [ 2. 6. 10.]
print(v.astype(int)) # [1 5 9] (truncates)
np.round(v, n)rounds to decimal places (halves go to the nearest even number, as in Python'sround).astype(int)converts the type and truncates.
d. Shape
The shape is the size of each dimension, as a tuple (rows, columns).
m = np.array([[1, 2, 3],
[4, 5, 6]])
print(m.shape) # (2, 3)
# 2 6 (dimensions, total items)
print(m.ndim, m.size)
r = m.reshape(3, 2) # same data, new shape
print(r) # [[1 2] [3 4] [5 6]]
print(m.reshape(-1)) # [1 2 3 4 5 6] (flattened)
print(m.T) # transpose: shape (3, 2)
grid = np.arange(12).reshape(3, 4) # a 3 x 4 grid
print(grid)
- The number of items must match when reshaping ().
-1means "work it out".- A shape mismatch in arithmetic raises a
ValueError.
e. Load and save text files
scores = np.array([[72, 85], [90, 64], [58, 77]])
np.savetxt("scores.txt", scores, fmt="%d", delimiter=",")
loaded = np.loadtxt("scores.txt", delimiter=",", dtype=int)
print(loaded.shape) # (3, 2)
print(np.array_equal(scores, loaded)) # True
np.savetxt(filename, array, fmt=..., delimiter=...)writes text, one row per line.np.loadtxt(filename, delimiter=",")reads it back (floats unlessdtypeis given).- Handle
FileNotFoundErrorandValueError(bad data). np.saveandnp.loaduse a binary.npyformat (faster, exact).
NumPy arrays and Python lists compared
| NumPy array | Python list | |
|---|---|---|
| Element types | All the same | Can be mixed |
| Arithmetic | Element by element, no loop | Needs loops ([1,2] + [3] joins lists) |
| Speed and memory | Fast, compact | Slower, bigger |
| Size | Fixed once created | Grows and shrinks |
| Best for | Numbers, matrices, big data | General collections |
Worked example
Task: four students have marks in three tests. Work out each student's average, each test's average, the overall highest mark, and the marks rounded after a 5% boost.
import numpy as np
marks = np.array([[60, 70, 80],
[55, 65, 75],
[90, 85, 95],
[40, 50, 45]])
print(marks.shape) # (4, 3)
# per student: [70. 65. 90. 45.]
print(marks.mean(axis=1))
# per test: [61.25 67.5 73.75]
print(marks.mean(axis=0))
print(marks.max()) # 95
boosted = np.round(marks * 1.05).astype(int)
print(boosted[0]) # [63 74 84]
axis=1averages across each row (per student);axis=0down each column (per test).marks * 1.05boosts every mark at once,np.roundrounds, andastype(int)gives whole numbers.- No loops were needed.
Exam tip: know that arithmetic is element by element, what shape and axis mean (axis 0 = down the rows, axis 1 = across the columns), and how to load and save. Say why NumPy is used (fast, compact, no loops).
Check yourself
What does np.array([1, 2, 3]) * 2 produce?
[2 4 6]: each element is multiplied by 2.
What is the shape of a 2D array with 3 rows and 4 columns?
(3, 4).
What does m.mean(axis=0) calculate on a 2D array?
The mean of each column (working down the rows).
Give two advantages of NumPy arrays over lists for numbers
They are faster and use less memory, and arithmetic applies to the whole array without loops.
Which functions save and load an array as a text file?
np.savetxt and np.loadtxt.