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.
import numpy as npCreating arrays¶
Create arrays from Python lists:
v = np.array([2.0, -1.0, 3.0])
A = np.array([
[1.0, 2.0, 0.0],
[3.0, -1.0, 4.0],
])
v, A(array([ 2., -1., 3.]),
array([[ 1., 2., 0.],
[ 3., -1., 4.]]))Every array has useful attributes:
print("v shape:", v.shape)
print("A shape:", A.shape)
print("A dimensions:", A.ndim)
print("A data type:", A.dtype)
print("A entries:", A.size)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:
zeros = np.zeros((2, 3))
identity = np.eye(3)
integers = np.arange(0, 10, 2)
grid = np.linspace(0, 1, 5)
zeros, identity, integers, grid(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.
A[0, 1]np.float64(2.0)Use : to select a range or an entire axis:
first_row = A[0, :]
second_column = A[:, 1]
block = A[:, 0:2]
first_row, second_column, block(array([1., 2., 0.]),
array([ 2., -1.]),
array([[ 1., 2.],
[ 3., -1.]]))Notice the shapes:
first_row.shape, second_column.shape, block.shape((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:
column_matrix = A[:, 1:2]
column_matrix, column_matrix.shape(array([[ 2.],
[-1.]]),
(2, 1))Copies and views¶
Some slices share data with the original array. Changing a slice may therefore change the original.
original = np.array([10, 20, 30, 40])
view = original[1:3]
view[0] = -20
originalarray([ 10, -20, 30, 40])Use .copy() when you need an independent array:
independent = original[1:3].copy()
independent[0] = 999
original, independent(array([ 10, -20, 30, 40]), array([999, 30]))Elementwise operations¶
Arithmetic operators act entry by entry when shapes are compatible.
x = np.array([1.0, 2.0, 3.0])
y = np.array([4.0, 5.0, 6.0])
x + y, 3 * x, x * y, x ** 2(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:
angles = np.array([0, np.pi / 2, np.pi])
np.sin(angles)array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])Vectorized code expresses an array calculation directly:
values = np.arange(1, 6)
squares = values ** 2
squaresarray([ 1, 4, 9, 16, 25])Aggregation and axis¶
An aggregation reduces several values to a summary.
M = np.array([
[1, 2, 3],
[4, 5, 6],
])
M.sum(), M.mean(), M.max()(np.int64(21), np.float64(3.5), np.int64(6))The axis argument specifies the axis that is collapsed:
column_sums = M.sum(axis=0)
row_sums = M.sum(axis=1)
column_sums, row_sums(array([5, 7, 9]), array([ 6, 15]))axis=0collapses rows and leaves one result per column.axis=1collapses columns and leaves one result per row.
Always check the output shape when learning an axis-based operation.
Boolean masks¶
A comparison with an array produces a Boolean array:
data = np.array([3.2, -1.0, 0.0, 4.5, -2.3])
positive_mask = data > 0
positive_mask, data[positive_mask](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.
observations = np.array([
[10.0, 100.0, 1.0],
[12.0, 120.0, 2.0],
[14.0, 140.0, 3.0],
])
column_means = observations.mean(axis=0)
centered = observations - column_means
column_means, centered(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:
numbers = np.arange(1, 7)
B = numbers.reshape(2, 3)
Barray([[1, 2, 3],
[4, 5, 6]])Transpose a matrix by exchanging rows and columns:
B.Tarray([[1, 4],
[2, 5],
[3, 6]])For a one-dimensional array, .T does not change the shape:
v = np.array([1, 2, 3])
v.shape, v.T.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.
X = np.array([
[2.0, 20.0],
[4.0, 30.0],
[8.0, 40.0],
[10.0, 50.0],
])Solution
means = X.mean(axis=0)
standard_deviations = X.std(axis=0)
Z = (X - means) / standard_deviations
Z, Z.mean(axis=0), Z.std(axis=0)(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
selected = X[X[:, 0] >= 5]
selectedarray([[ 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).shapeSolution
The shapes are (3,), (4, 1), (3,), and (4,), respectively.