2

I have an array of 2d indices.

indices = [[2,4], [6,77], [102,554]]

Now, I have a different 4-dimensional array, arr, and I want to only extract an array (it is an array, since it is 4-dimensional) with corresponding index in the indices array. It is equivalent to the following code.

for i in range(len(indices)):
    output[i] = arr[indices[i][0], indices[i][1]]

However, I realized that using explicit for-loop yields a slow result. Is there any built-in numpy API that I can utilized? At this point, I tried using np.choose, np.put, np.take, but did not succeed to yield what I wanted. Thank you!

2 Answers 2

1

We need to index into the first two axes with the two columns from indices (thinking of it as an array).

Thus, simply convert to array and index, like so -

indices_arr = np.array(indices)
out = arr[indices_arr[:,0], indices_arr[:,1]]

Or we could extract those directly without converting to array and then index -

d0,d1 = [i[0] for i in indices], [i[1] for i in indices]
out = arr[d0,d1]

Another way to extract the elements would be with conversion to tuple, like so -

out = arr[tuple(indices_arr.T)]

If indices is already an array, skip the conversion process and use indices in places where we had indices_arr.

Sign up to request clarification or add additional context in comments.

2 Comments

Is the first method faster than using the explicit for-loop?
@AverageAlgorithmGuy If you already have indices as an array, I would go with the first approach, else go with the second one.
0

Try using the take function of numpy arrays. Your code should be something like:

outputarray= np.take(arr,indices)

1 Comment

From the numpy docs: "If indices is not one dimensional, the output also has these dimensions." That means it will return [[arr[indices[0][0]], arr[indices[0][1]], ...], [arr[indices[1][0]], arr[indices[1][1]], ...], ...]

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.