Numpy extract submatrix

print y[0:4:3,0:4:3]

is the shortest and most appropriate fix .


Give np.ix_ a try:

Y[np.ix_([0,3],[0,3])]

This returns your desired result:

In [25]: Y = np.arange(16).reshape(4,4)
In [26]: Y[np.ix_([0,3],[0,3])]
Out[26]:
array([[ 0,  3],
       [12, 15]])

One solution is to index the rows/columns by slicing/striding. Here's an example where you are extracting every third column/row from the first to last columns (i.e. the first and fourth columns)

In [1]: import numpy as np
In [2]: Y = np.arange(16).reshape(4, 4)
In [3]: Y[0:4:3, 0:4:3]
Out[1]: array([[ 0,  3],
               [12, 15]])

This gives you the output you were looking for.

For more info, check out this page on indexing in NumPy.

Tags:

Python

Numpy