如何使用字典在python中转换数组?

时间:2018-10-16 17:52:46

标签: python python-3.x numpy

作为一个玩具示例,假设我有:

import numpy as np

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

我想找到一种有效的方法来构造所需的数组,在该数组中我根据字典替换了元素。

(真正的字典是元素周期表,真正的数组有数千个元素)

2 个答案:

答案 0 :(得分:5)

您可以vectorize字典的get方法。

>>> 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]])

我将dict重命名为d,因为您不应使用自己的变量遮盖内置名称dict

答案 1 :(得分:1)

您的意思是这样的吗?这将在创建numpy数组之前替换值:

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']],
])

还是您需要更笼统的内容?