Reputation: 143
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.
Upvotes: 1
Views: 977
Reputation: 114230
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]]
Upvotes: 2