the full guide

NumPy: fast numbers

Arrays, shapes, maths on whole arrays, and the tools every ML library is built on.

15 min Beginner

What you need: The earlier pages of this course. Nothing to install.

Arrays

A NumPy array is like a list made for maths. Do something to the array, and it happens to every number, without a loop.

numpy_basics.py
import numpy as np

marks = np.array([78, 85, 90, 62])

print(marks + 5)         # Adds to every item
print(marks * 2)
print(marks.mean(), marks.max(), marks.std().round(2))
print(marks[marks >= 80])    # Only the items that pass the test

Output

[83 90 95 67]
[156 170 180 124]
78.75 90 10.57
[85 90]

Rows, columns and shape

numpy_shape.py
import numpy as np

table = np.array([[1, 2, 3],
                  [4, 5, 6]])

print(table.shape)          # (rows, columns)
print(table[0, 2])          # Row 0, column 2
print(table[:, 1])          # All of column 1
print(table.sum(axis=0))    # Add down each column
print(table.sum(axis=1))    # Add across each row
print(table.reshape(3, 2))
print(np.dot([1, 2], [3, 4]))   # 1×3 + 2×4

Output

(2, 3)
3
[2 5]
[5 7 9]
[ 6 15]
[[1 2]
 [3 4]
 [5 6]]
11

Finished reading?