Home > database >  Python: replace values in a 2d array from another 1d array based on some conditions
Python: replace values in a 2d array from another 1d array based on some conditions

Time:06-09

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!

CodePudding user response:

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.

CodePudding user response:

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)

CodePudding user response:

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.

  • Related