Represent numerical data efficiently and perform operations on whole collections.

NumPy arrays and vector operations

Learning objectives

  • Create one-dimensional and two-dimensional arrays.
  • Inspect shape and data type.
  • Apply an operation to every element.
  • Calculate a simple summary without writing a manual loop.

Install NumPy in the project environment:

python -m pip install numpy

Arrays

import numpy as np

temperatures = np.array([18, 20, 21, 19])
print(temperatures.shape)
print(temperatures + 2)
print(temperatures.mean())
(4,)
[20 22 23 21]
19.5

The shape (4,) means four values in one dimension. Adding 2 applies to every element. This is called vectorized computation.

Two dimensions

readings = np.array([
    [18, 20, 21],
    [19, 22, 23],
])

print(readings.shape)
print(readings[:, 1])
print(readings.mean(axis=0))
(2, 3)
[20 22]
[18.5 21.  22. ]

readings[:, 1] selects every row from column one. axis=0 calculates a result for each column.

Practice

Create an array of five robot distances in centimeters. Calculate the minimum, maximum, mean, and a boolean array showing which readings are below 20 cm.

Common mistakes

  • Confusing shape with the number of elements.
  • Mixing centimeters and meters.
  • Treating a missing measurement as a real zero.
  • Forgetting that array slices can share data with the original array.

Checkpoint

What does axis=0 mean for a table with rows as observations and columns as measurements? Explain in words before using it.

See the NumPy documentation for arrays and indexing.