Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

0.3 NumPy Arrays

NumPy arrays store numerical data in a rectangular structure. A one-dimensional array can represent a vector, and a two-dimensional array can represent a matrix.

Creating arrays

Create arrays from Python lists:

(array([ 2., -1., 3.]), array([[ 1., 2., 0.], [ 3., -1., 4.]]))

Every array has useful attributes:

v shape: (3,)
A shape: (2, 3)
A dimensions: 2
A data type: float64
A entries: 6

The matrix A has shape (2, 3): 2 rows and 3 columns. Shape determines whether many operations are valid.

NumPy also provides constructors for common arrays:

(array([[0., 0., 0.], [0., 0., 0.]]), array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]), array([0, 2, 4, 6, 8]), array([0. , 0.25, 0.5 , 0.75, 1. ]))

Indexing and slicing

For a matrix, write the row index first and the column index second.

np.float64(2.0)

Use : to select a range or an entire axis:

(array([1., 2., 0.]), array([ 2., -1.]), array([[ 1., 2.], [ 3., -1.]]))

Notice the shapes:

((3,), (2,), (2, 2))

Both a selected row and a selected column are one-dimensional here. To preserve a two-dimensional column shape, select a one-column slice:

(array([[ 2.], [-1.]]), (2, 1))

Copies and views

Some slices share data with the original array. Changing a slice may therefore change the original.

array([ 10, -20, 30, 40])

Use .copy() when you need an independent array:

(array([ 10, -20, 30, 40]), array([999, 30]))

Elementwise operations

Arithmetic operators act entry by entry when shapes are compatible.

(array([5., 7., 9.]), array([3., 6., 9.]), array([ 4., 10., 18.]), array([1., 4., 9.]))

Here x * y is elementwise multiplication. It is not a dot product and not matrix multiplication.

Many NumPy functions are vectorized:

array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])

Vectorized code expresses an array calculation directly:

array([ 1, 4, 9, 16, 25])

Aggregation and axis

An aggregation reduces several values to a summary.

(np.int64(21), np.float64(3.5), np.int64(6))

The axis argument specifies the axis that is collapsed:

(array([5, 7, 9]), array([ 6, 15]))

Always check the output shape when learning an axis-based operation.

Boolean masks

A comparison with an array produces a Boolean array:

(array([ True, False, False, True, False]), array([3.2, 4.5]))

Masks support data filtering without a manual loop.

Broadcasting

Broadcasting lets NumPy combine compatible shapes by treating a smaller array as if it were repeated.

(array([ 12., 120., 2.]), array([[ -2., -20., -1.], [ 0., 0., 0.], [ 2., 20., 1.]]))

observations has shape (3, 3) and column_means has shape (3,). NumPy subtracts the three means from each row.

Broadcasting compares dimensions from right to left. Two dimensions are compatible when they are equal or one of them is 1.

Reshaping and transposing

Reshape an array without changing its entries:

array([[1, 2, 3], [4, 5, 6]])

Transpose a matrix by exchanging rows and columns:

array([[1, 4], [2, 5], [3, 6]])

For a one-dimensional array, .T does not change the shape:

((3,), (3,))

Use v.reshape(-1, 1) when a genuine column-shaped array is required.

Practice

Exercise 1: standardize each column

For the array below, subtract each column’s mean and divide by that column’s standard deviation. The result should have column means near zero.

Solution
(array([[-1.26491106, -1.34164079], [-0.63245553, -0.4472136 ], [ 0.63245553, 0.4472136 ], [ 1.26491106, 1.34164079]]), array([5.55111512e-17, 0.00000000e+00]), array([1., 1.]))

The standardized columns have means close to 0 and standard deviations close to 1.

Exercise 2: select rows

Select every row of X whose first entry is at least 5.

Solution
array([[ 8., 40.], [10., 50.]])

Exercise 3: predict shapes

Predict each shape before running the code:

C = np.zeros((4, 3))
C[1, :].shape
C[:, 1:2].shape
C.mean(axis=0).shape
C.mean(axis=1).shape
Solution

The shapes are (3,), (4, 1), (3,), and (4,), respectively.