1

I have two arrays of variable length and content (simplified example):

A = np.array([[0.25, 0.25], [0.25, 0.75], [0.75, 0.25], [0.75, 0.75], [0.8, 0.9] ...]) 
B = np.array([0, 1, 2, 4, 0, 3, 3, ...])

What is the best/fastest way to get an array where every element of B is replaced with the corresponding row from A (B as index) so that the result would be:

C = [[0.25, 0.25], [0.25, 0.75], [0.75, 0.25], [0.8, 0.9], [0.25, 0.25], [0.75, 0.75], [0.75, 0.75], ...]

I am somehow at a loss (still a beginner with problems getting my head around numpy).

Edit/addendum: Forgot to mention: I would like to avoid loops since the arrays are big and time is critical.

0

1 Answer 1

2

You can just use direct indexing:

C = A[B, :]

Results in

[[ 0.25  0.25]
 [ 0.25  0.75]
 [ 0.75  0.25]
 [ 0.8   0.9 ]
 [ 0.25  0.25]
 [ 0.75  0.75]
 [ 0.75  0.75]]

IDEOne Link

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

2 Comments

Thx, exactly what i was looking for. Hope i will some day get a better grasp of Numpy. :)
@kukuschi. Keep using it and you will. It's inevitable.

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.