0

thanks in advance for your help! I would like to the do the following, but I am new to Python, kind of unsure what to do efficiently.

  1. I have a 2d array, for example A=[[1,1],[2,3]].
  2. Each value in the above 2d array corresponds to the index in another 1d array, for example: B=[0.1,0.2,0.8,0.9].
  3. The end result should be like: C=[[0.2,0.2],[0.8,0.9]]. That means, C[i,j]=B[index=A[i,j]].

The above is a simple example. But in practice, A can be a huge array, so I would really appreciate if there is any way to do this efficiently. Thank you!

3 Answers 3

2

According to your post, you already almost got the answer. If you are really looking for a one line code, you can do this.

c = B[A]

c
Out[24]: 
array([[0.2, 0.2],
       [0.8, 0.9]])

The code above is for numpy array. On the other hand, if it is a list, list comprehension would be required.

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

Comments

1

First try planning the sequence from index of first list and the relation with the result list.

A = [[1,1],[2,3]]
B=[0.1,0.2,0.8,0.9]

C = [[B[i] for i in j] for j in A]

print(C)

3 Comments

Isn't there a way to do this without a loop in numpy?
Really thanks for your help! But I am wondering is there any way to vectorize such a loop? Thanks!
@QuVergil I edited my answer for a shorter. I hope that it's that you mean
1

Based on your comments on answer by @PAUL ANDY DE LA CRUZ YANAC, I see that you are trying to use numpy and avoid for loop but as far as my knowledge, you need to use a for loop at least once.

import numpy as np

for x, y in np.ndindex(np.array(A).shape):
    A[x][y] = B[A[x][y]]

Note: This approach changes the original list A. But if you want to create a new list, look at the solution by @Paul Dlc.

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.