2

I have a numpy multidimensional array with shape = (12,2,3,3)

import numpy as np
arr = np.arange(12*2*3*3).reshape((12,2,3,3))

I need to select those elements based on the 2nd dimension where the dindices are stored in another list

indices = [0,1,0,0,1,1,0,1,1,0,1,1]

in one array, and the rest in another array. the output in either case should be in another array of shape (12,3,3)

arr2 = np.empty((arr.shape[0],*arr.shape[-2:]))

I could do it using a for loop

for i, ii in enumerate(indices):
    arr2[i] = arr[i, indices[ii],...]

However, I am searching for a one liner.

When I try indexing using the list as indices

test = arr[:,indices,...]

I get test of shape (12,12,3,3) instead of (12,3,3). Could you help me please?

1

1 Answer 1

2

You can use np.arange for indexing the first dimension:

test = arr[np.arange(arr.shape[0]),indices,...]

or just the python range function:

test = arr[range(arr.shape[0]),indices,...]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.