根据键映射numpy数组中的某些值

时间:2019-11-22 19:50:54

标签: python numpy mapping numpy-ndarray

我想使用numpy的数组编程样式,即没有任何循环(至少在我自己的代码中),根据映射字典将一些数组值转换为其他值。这是我想出的代码:

>>> characters
# Result: array(['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'])
mapping = {'a':'0', 'b':'1', 'c':'2'}
characters = numpy.vectorize(mapping.get)(characters)

因此,基本上我想将每个“ a”字母替换为“ 0”等。但是由于我只希望替换一些值,所以我不提供映射,因此它不起作用信件。我总是可以使用一个循环,该循环基于映射来遍历字典条目并替换数组中的新值,但是我不允许使用循环。

您有任何想法如何使用这种数组编程样式解决它吗?

1 个答案:

答案 0 :(得分:1)

IIUC,您只需要提供get的默认值,否则结果为None。可以使用lambda函数完成此操作,例如:

import numpy as np

characters = np.array(['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'])
mapping = {'a': '0', 'b': '1', 'c': '2'}

translate = lambda x: mapping.get(x, x)

characters = np.vectorize(translate)(characters)

print(characters)

输出

['H' 'e' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']

针对:

characters = np.array(['H', 'a', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'])

输出

['H' '0' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
相关问题