Nataly
Nataly

Reputation: 333

How to substitute values from array to values in list in Python?

I have an array (of numpy.ndarray type) like

arr=array([[1, 5, 1],
          [4, 2, 0]])

and a list of values:

values=['father','mother','sister','brother','aunt','uncle']

And I'd like to substitute numbers in array arr with items from list values using array's items as indices of list values:arr[0,0]=values[arr[0,0]]

Here an example of what I'd like to have

arr=array([['mother', 'uncle', 'mother'],
           ['aunt', 'sister', 'father']])

Is there any elegant pythonic way to do this?

Thanks for helping in advance =)

Upvotes: 2

Views: 114

Answers (2)

B. M.
B. M.

Reputation: 18668

use the numpy take function :

In [64]: np.take(values,arr)
Out[64]: 
array([['mother', 'uncle', 'mother'],
       ['aunt', 'sister', 'father']], 
      dtype='<U7')

The conversion is then automatic.

Upvotes: 1

Kasravnd
Kasravnd

Reputation: 107347

You can convert the values to a numpy array then use a simple indexing:

>>> values = np.array(values)
>>> 
>>> values[arr]
array([['mother', 'uncle', 'mother'],
       ['aunt', 'sister', 'father']], 
      dtype='|S7')

Read more about indexing: http://docs.scipy.org/doc/numpy-1.10.0/reference/arrays.indexing.html

Upvotes: 2

Related Questions