Member-only story
Indexing and slicing numpy arrays
In this section we will look at indexing and slicing. These work in a similar way to indexing and slicing with standard Python lists, with a few differences
Indexing an array
Indexing is used to obtain individual elements from an array, but it can also be used to obtain entire rows, columns or planes from multi-dimensional arrays.
Indexing in 1 dimension
We can create 1 dimensional numpy array from a list like this:
import numpy as np
a1 = np.array([1, 2, 3, 4])
print(a1) # [1, 2, 3, 4]
We can index into this array to get an individual element, exactly the same as a normal list or tuple:
print(a1[0]) # 1
print(a1[2]) # 3
Indexing in 2 dimensions
We can create a 2 dimensional numpy array from a python list of lists, like this:
import numpy as np
a2 = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
Here is a diagram of the array:
We can index an element of the array using two indices — i selects the row, and j selects the column:
print(a2[2, 1]) # 8