This problem stems from learning about indexes and slicing in NumPy. The books and tutorials only mention how to index a row, but not how to index a column in an array. Think of this matrix as a 3 by 3 array, so how do I get some submatrix of this matrix?


First let’s review how indexing is done in NumPy. An index of a one-dimensional array, roughly like a list in Python, can be obtained by fetching the value of an element, and can also be changed numerically.

import numpy as np
x_1 = np.array([1.2.3.4.5.6.7.8.9]) Create a two-dimensional array
x_1[1] Extract an element from a one-dimensional array
x_1[1:3] Extract elements 2 through 4
Copy the code

For a two-dimensional array, the same method is used to extract a one-dimensional array instead of a scalar, so how can we extract elements in rows and columns of np.array? The general idea is to get the row data we want, and then get the column data we want. Again, if we want to get a subset of the array in rows 1 and 3 and columns 2 and 3, we can get rows 1 and 3 first, and columns 2 and 3 later.


import numpy as np
X_2 = np.array([[1.2.3], [4.5.6], [7.8.9]])
E = [0.2] # define the number of rows
F = [1.2] Define the number of columns
X_3 = X_2[E] First fetch the required rows
X_3 = X_3[:F] # exit the desired column
print(X_3)
Copy the code

The result looks like this:

array([[2, 3],
       [8, 9]])
Copy the code