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)

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.