Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy: Swap value in 2D numpy array

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading