Sub topic 1
NumPy Indexing, Slicing, and Boolean Masks
Prerequisites
Assume you know basic Python lists and slicing, and can create NumPy arrays with np.array, np.arange, and reshape. You should also know that an array has a shape and a data type (dtype).
Array shape and axes: what an index addresses
A NumPy array is an ndarray, an object that stores values in one or more dimensions. Its shape gives the length of each dimension. Each dimension has an axis number starting at zero.
import numpy as np
a = np.arange(12).reshape(3, 4)
print(a)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a.shape) # (3, 4)Axis 0 addresses rows, and axis 1 addresses columns.
Selecting single elements with integer indices
Integer indices select one position. NumPy uses zero-based indexing, so the first row and column are both numbered 0.
print(a[1, 2]) # 6
print(a[-1, 0]) # 8The first index addresses axis 0. The second addresses axis 1. Integer indexing removes the addressed axes, so a[1] returns one-dimensional row with shape (4,).
Slicing arrays: start, stop, step, and negative indices
A slice has the form start:stop:step. The stop position is excluded. You can omit any part.
print(a[0:2, 1:3])
# [[1 2]
# [5 6]]
print(a[:, -1]) # [ 3 7 11]
print(a[::2, ::-1])
# [[ 3 2 1 0]
# [11 10 9 8]]A negative index counts from the end. A negative step moves backward.
Ellipsis and `np.newaxis`
An ellipsis (...) represents as many full-axis slices as needed. It is useful with arrays containing many dimensions. np.newaxis adds a dimension of length one.
print(a[..., 0]) # first column
print(a[np.newaxis, :, :].shape) # (1, 3, 4)
print(a[:, :, np.newaxis].shape) # (3, 4, 1)Exercise
What are the shape and value of a[1:, 2] for the array above?
Show answer
Its shape is (2,), and its value is [6, 10].