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

Python 根据键映射numpy数组中的某些值,python,numpy,mapping,numpy-ndarray,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)(char

我想基于映射字典,使用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)
因此,基本上我想用“0”等替换每个“a”字母。但由于我只想替换一些值,所以我没有为每个字母提供映射,因此它不起作用。我总是可以使用循环来迭代字典条目,并根据映射替换数组中的新值,但我不允许使用循环


你知道我如何使用这种数组编程风格来解决它吗?

IIUC,你只需要为提供一个默认值,否则结果是
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']
['H' '0' 'l' 'l' 'o' ' ' 'W' 'o' 'r' 'l' 'd']
用于:

输出

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

那么你在转换索引吗?像索引0到“a”一样?或者反过来,“a”变成“0”?也许您可以发布一个预期的输出;-)您可以添加一个实际替换某些内容的输出吗?我添加了解释,我只是想用“0”等替换每个字母“a”。