Separius
Separius

Reputation: 1296

Select different slices from each numpy row

I have a 3d tensor and I want to select different slices from the dim=2. something like a[[0, 1], :, [slice(2, 4), slice(1, 3)]].

a=np.arange(2*3*5).reshape(2, 3, 5)
array([[[ 0,  1,  2,  3,  4],
        [ 5,  6,  7,  8,  9],
        [10, 11, 12, 13, 14]],

       [[15, 16, 17, 18, 19],
        [20, 21, 22, 23, 24],
        [25, 26, 27, 28, 29]]])
# then I want something like a[[0, 1], :, [slice(2, 4), slice(1, 3)]]
# that gives me np.stack([a[0, :, 2:4], a[1, :, 1:3]]) without a for loop
array([[[ 2,  3],
        [ 7,  8],
        [12, 13]],

       [[16, 17],
        [21, 22],
        [26, 27]]])

and I've seen this and it is not what I want.

Upvotes: 2

Views: 1010

Answers (2)

Sheldore
Sheldore

Reputation: 39042

You can use advanced indexing as explained here. You will have to pass the row ids which are [0, 1] in your case and the column ids 2, 3 and 1, 2. Here 2,3 means [2:4] and 1, 2 means [1:3]

import numpy as np
a=np.arange(2*3*5).reshape(2, 3, 5)

rows = np.array([[0], [1]], dtype=np.intp)
cols = np.array([[2, 3], [1, 2]], dtype=np.intp)

aa = np.stack(a[rows, :, cols]).swapaxes(1, 2)
# array([[[ 2,  3],
#         [ 7,  8],
#         [12, 13]],

#        [[16, 17],
#         [21, 22],
#         [26, 27]]])

Another equivalent way to avoid swapaxes and getting the result in desired format is

aa = np.stack(a[rows, :, cols], axis=2).T

A third way I figured out is by passing the list of indices. Here [0, 0] will correspond to [2,3] and [1, 1] will correspond to [1, 2]. The swapaxes is just to get your desired format of output

a[[[0,0], [1,1]], :, [[2,3], [1,2]]].swapaxes(1,2)

Upvotes: 2

godot
godot

Reputation: 1570

A solution...

import numpy as np
a = np.arange(2*3*5).reshape(2, 3, 5)
np.array([a[0,:,2:4], a[1,:,1:3]])

Upvotes: -1

Related Questions