2

I have an array in three dimensions (x, y, z) and an indexing vector. This vector has a size equal to the dimension x of the array. Its objective is to index a specific y bringing their respective z, i.e., the expected result has dimension (x, z).

I wrote a code that works as expected, but does anyone know if a Numpy function can replace the for loop and solve the problem more optimally?

arr = np.random.rand(100,5,2)
result = np.random.rand(100,2)
id = [np.random.randint(0, 5) for _ in range(100)]
for i in range(100): 
    result[i] = arr[i,id[i]]

1 Answer 1

1

You can achieve this with this piece of code:

import numpy as np
arr = np.random.randn(100, 5, 2)
ids = np.random.randint(0, 5, size=100)
res = arr[range(100), ids]
res.shape # (100, 2)
Sign up to request clarification or add additional context in comments.

1 Comment

Not sure if OP meant to only index the y dimension. If so the first dimension will not be indexed: res = arr[:, ids].

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.