作为一个玩具示例,假设我有:
import numpy as np
np.array([['dog','sheep','sheep','dog','cat'],
['dog','dog','sheep','cat','cat']])
dict = {'dog':5,'cat':1,'sheep':3}
我想找到一种有效的方法来构造所需的数组,在该数组中我根据字典替换了元素。
(真正的字典是元素周期表,真正的数组有数千个元素)
答案 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']],
])
还是您需要更笼统的内容?