Home > Software engineering >  How to replace values of a 2d array with values of a list based on index
How to replace values of a 2d array with values of a list based on index

Time:09-28

I am wondering if I can replace elements of a 2d array with elements of a list based on the index in Python:

let's say

a = np.array([[6, 5, 9, 6, 1],[2, 9, 0, 6, 5],[8, 8, 0, 1, 8],[9, 5, 3, 6, 3]])
d = ['a','b','c','d','e','f','g','h','i','j]

I want to replace the elements of array a with the elements of list d. Values of array a define the index number of list d.

I want a 2d array like c,

c = np.array([['g','f','j','g','b'],['c','j','a','g','e'],['i','i','a','b','i'],['j','f','d','g','d']])

CodePudding user response:

You can use a simple loop:

a=np.array([[6, 5, 9, 6, 1],[2, 9, 0, 6, 5],[8, 8, 0, 1, 8],[9, 5, 3, 6, 3]])
d=['a','b','c','d','e','f','g','h','i','j']
 
all_value = []
for i in a:
    value = []
    for j in i:
        value.append(d[j])
    all_value.append(value)
np.array(all_value)

CodePudding user response:

You can do it in multiple ways actually.

First way is to use list comprehension:

import numpy as np
    
a = np.array([[6, 5, 9, 6, 1],
              [2, 9, 0, 6, 5],
              [8, 8, 0, 1, 8],
              [9, 5, 3, 6, 3]
              ])
                  
d = np.array(['a','b','c','d','e','f','g','h','i','j'])
    
c = np.array([[d[j] for j in a[i]] for i in range(len(a))])

You can also use the following:

import numpy as np

a = np.array([[6, 5, 9, 6, 1],
              [2, 9, 0, 6, 5],
              [8, 8, 0, 1, 8],
              [9, 5, 3, 6, 3]
              ])
          
d = np.array(['a','b','c','d','e','f','g','h','i','j'])

c = d[a[:]]

You can also go for a for loop driven code, but if you choose to do that then I would advice you to ditch that and go for list comprehension.

CodePudding user response:

Try this:

>>> a=np.array([[6, 5, 9, 6, 1],[2, 9, 0, 6, 5],[8, 8, 0, 1, 8],[9, 5, 3, 6, 3]])
>>> d=np.array(['a','b','c','d','e','f','g','h','i','j'])
>>> d[a]
array([['g', 'f', 'j', 'g', 'b'],
       ['c', 'j', 'a', 'g', 'f'],
       ['i', 'i', 'a', 'b', 'i'],
       ['j', 'f', 'd', 'g', 'd']], dtype='<U1')
>>> list(map(list,(d[a])))
[['g', 'f', 'j', 'g', 'b'],
 ['c', 'j', 'a', 'g', 'f'],
 ['i', 'i', 'a', 'b', 'i'],
 ['j', 'f', 'd', 'g', 'd']]
  • Related