Search code examples
pythonpython-3.xnumpynumpy-indexing

python index in 2d matrix


Given the following code:

import numpy as np
mat = np.arange(1,26).reshape(5,5)

My understanding was the following lines are identical:

mat[:3][1:2]
mat[:3,1:2]

But they are not. Why?


Solution

  • If you only specify one dimension in your slicing syntax, only one dimension will be sliced. In NumPy, dimensions in indexing are typically separated by ",".

    For a 2d array, you may substitute "row" with "dimension 1" and "column" with "dimension 2". In your example, mat[:3] slices the first 3 rows. The subsequent indexer [1:2], slices the first of those 3 rows.

    With your second example, [:3, 1:2] slices rows and columns simultaneously.

    You may find it helpful to look at the shapes of your results:

    mat[:3].shape       # (3, 5)
    mat[:3][1:2].shape  # (1, 5)
    mat[:3,1:2].shape   # (3, 1)