Naomi Fridman
Naomi Fridman

Reputation: 2144

Slice array of arbitrary dimension with lists of start and end indices

I need to copy a part of a 3D array. I have the indexes of start and end of the copy.

For example 2D array:

[[2 2 3 4 5]
 [2 3 3 4 5]
 [2 3 4 4 5]
 [2 3 4 5 5]
 [2 3 4 5 6]]

starting index, end index are:

mini = [2, 1]
maxi = [4, 3]

So the result should be:

  [[3 4 4]
   [3 4 5]]

I can write:

result = matrix[mini[0]:maxi[0], mini[1]:maxi[1]]

Is there a way to do it generally ? for 3Dim or NDim arrays ?

Upvotes: 1

Views: 166

Answers (2)

jadsq
jadsq

Reputation: 3382

What you are looking for is the slice object, see that example:

matrix = np.random.rand(4,5)
mini = [2, 1]
maxi = [4, 3]
slices=[slice(b,e) for b, e in zip(mini,maxi)]
print(slices)
print(matrix[slices])
print(matrix[mini[0]:maxi[0], mini[1]:maxi[1]])

Upvotes: 0

Eric
Eric

Reputation: 97565

The trick here is realizing what the indexing syntax is under the hood. This:

result = matrix[mini[0]:maxi[0], mini[1]:maxi[1]]

Is shorthand in python (not just numpy) for:

indices = slice(mini[0], maxi[0]), slice(mini[1], maxi[1])
result = matrix[indices]

So we just need to generate indices dynamically:

lower = [2, 1, ...]
upper = [4, 3, ...]

indices = tuple(np.s_[l:u] for l, u in zip(lower, upper))
result = matrix_nd[indices]

np.s_[a:b] is a shorthand for slice(a, b). Here we build a tuple containing as many slices as you have values in lower and upper

Upvotes: 2

Related Questions