alex
alex

Reputation: 11400

Get NumPy slice from start/end coordinates

Let's say I have a 3D 100x100x100 array and have some starting and ending coordinates, e.g.:

(0,0,0) (50,20,20)

How can I get extract a subarray bounded by cuboid defined by those vertices?

Upvotes: 2

Views: 350

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

We can use slicing notation. For this specific case that would be:

subarray = the_array[0:50, 0:20, 0:20]

Of course the above will only work given we know the numbers (and dimension) in advance. A more sophisticated program is necessary if we are given two three-tuples:

first = (0,0,0)
second = (50,20,20)

a0, b0, c0 = first
a1, b1, c1 = second
subarray = the_array[a0:a1, b0:b1, c0:c1]

But this is still not very elegant, since we hardcode the number of dimensions. We can process two tuples (or iterables in general) of arbitrary size for that:

first = (0,0,0)
second = (50,20,20)

subarray = the_array[tuple(slice(x,y) for x, y in zip(first, second))]

The upperbounds in slicing are always exclusive. In case you want to add these, you can increment the upperbound:

subarray = the_array[0:51, 0:21, 0:21]

or:

subarray = the_array[a0:a1+1, b0:b1+1, c0:c1+1]

or:

subarray = the_array[tuple(slice(x,y+1) for x, y in zip(first, second))]

Upvotes: 2

Related Questions