1

As a toy example let's say that I have:

import numpy as np

np.array([['dog','sheep','sheep','dog','cat'], 
          ['dog','dog','sheep','cat','cat']])
dict = {'dog':5,'cat':1,'sheep':3}

I want to find an efficient way to construct the desired array where I replaced the elements according to the dictionary.

(The real dictionary is the periodic table and the real array has thousands of elements)

Goods
  • 225
  • 2
  • 10
  • Possible duplicate of [How to apply a function / map values of each element in a 2d numpy array/matrix?](https://stackoverflow.com/questions/42594695/how-to-apply-a-function-map-values-of-each-element-in-a-2d-numpy-array-matrix) – a_guest Oct 16 '18 at 17:58

2 Answers2

5

You can vectorize the dict's get method.

>>> import numpy as np
>>> a = np.array([['dog','sheep','sheep','dog','cat'], 
...               ['dog','dog','sheep','cat','cat']])
>>> d = {'dog':5,'cat':1,'sheep':3}
>>> 
>>> np.vectorize(d.get)(a)
array([[5, 3, 3, 5, 1],
       [5, 5, 3, 1, 1]])

I have renamed dict to d because you should not shadow the builtin name dict with your own variables.

timgeb
  • 76,762
  • 20
  • 123
  • 145
1

You mean something like this? This replaces the values before creating the numpy array:

import numpy as np
my_dict = {'dog': 5, 'cat': 1, 'sheep': 3}

np.array([
    [my_dict[e] for e in ['dog','sheep','sheep','dog','cat']],
    [my_dict[e] for e in ['dog','dog','sheep','cat','cat']],
])

Or do you need something more generalized?

Ralf
  • 16,086
  • 4
  • 44
  • 68