Home > OS >  Numpy: Swap value in 2D numpy array
Numpy: Swap value in 2D numpy array

Time:02-24

I have a 2D numpy array:

arr = np.array(([[6,1,2],
                 [3,4,5],
                 [0,7,8]]))

I use a other 1D numpy array:

value = np.asarray([9,8,7,6,5,4,3,2,1])

I would like to change the values ​​of my 2D array with the index value of my 1D array

For example:

In my 2D array at position (0,0), I have the value 6. I must therefore modify the value (0,0) by the value present at index 6 of my 1D array, therefore 3.

So far I have this code:

value = np.asarray([9,8,7,6,5,4,3,2,1])
arr = np.array(([[6,1,2],[3,4,5],[0,7,8]]))

print(arr)
#[[6 1 2]
#[3 4 5]
#[0 7 8]]

for i in range(arr.shape[0]):
    for j in range(arr.shape[1]):
        arr[i,j] = value[arr[i,j]]

print(arr)

#[[3 8 7]
#[6 5 4]
#[9 2 1]]

The problem is that this code takes time on large tables. (10 seconds for an array of size 4096²)

Is there an effective way to solve this problem?

CodePudding user response:

This is very simple, you just need a single command. Numpy automatically takes care of the vectorization.

arr = value[arr]

Here is an example with the data you provided:

>>> value[arr]
array([[3, 8, 7],
       [6, 5, 4],
       [9, 2, 1]])
  • Related