Is there a numpy function for finding the range between two vectors in an array

Question:

Is there a function in numpy, that returns the part between two vectors:

ex:
Say this table shows the array

1 2 3
4 5 6
7 8 9

Is there such a function when called like array[(0, 1): (2, 3)] will return

2 3
5 6

where two end points are the vectors specified in the range. (0, 1) is the topleft end, and (2, 3) is the bottomright end. The vectors’ sizes are unknown as well as the shape of the matrix.

Asked By: Hüseyin Şimşek

||

Answers:

In (0, 1), the 0 refers to the row, and the 1 refers to the column.
In (2, 3), the 2 refers to the row, and the 3 refers to the column.

You can’t directly use (0, 1) and (2, 3), but recognizing the above, you can convert them to slices. You can also pass a tuple of slices to the array indexer, and it’ll use the ith slice along the ith axis.

def special_slice(array, topleft, bottomright):
    slices = tuple(slice(tl, br) for tl, br in zip(topleft, bottomright))
    return array[slices]

a = np.array([[1., 2., 3.],
              [4., 5., 6.],
              [7., 8., 9.]])

b = special_slice(a, (0, 1), (2, 3))
# array([[2., 3.],
#        [5., 6.]])
Answered By: Pranav Hosangadi

You can use regular subscripting. The range values simply need to be grouped by rows and column start/stop pairs:

import numpy as np

x= np.array([[1., 2., 3.],
             [4., 5., 6.],
             [7., 8., 9.]])

top    = (0,1)
bottom = (2,3)

r0,c0,r1,c1 = *top,*bottom
y = x[r0:r1,c0:c1]

print(y)
[[2. 3.]
 [5. 6.]]

If you have a variable number of dimensions in the matrix, you can use starmap from itertools to convert the coordinates to slices for subscripting:

from itertools import starmap

y = x[(*starmap(slice,zip(top,bottom)),)]
Answered By: Alain T.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.