简体   繁体   English

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

[英]Mapping some of the values in a numpy array according to keys

I want to transform some of the array values to other values, based on mapping dictionary, using numpy's array programming style, ie without any loops (at least in my own code).我想将一些数组值转换为其他值,基于映射字典,使用 numpy 的数组编程风格,即没有任何循环(至少在我自己的代码中)。 Here's the code I came up with:这是我想出的代码:

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

So basically I want to replace every 'a' letter with '0' etc. But it doesn't work due to the fact that I want only some of the values to be replaced so I didn't provide mapping for every letter.所以基本上我想用“0”等替换每个“a”字母。但它不起作用,因为我只想替换一些值,所以我没有为每个字母提供映射。 I could always use a loop that iterates over the dictionary entries and substitutes new values in the array, based on mapping, but I'm not allowed to use loops..我总是可以使用循环遍历字典条目并根据映射替换数组中的新值,但我不允许使用循环..

Do you have any ideas how could I tackle it using this array programming style?你有什么想法我如何使用这种数组编程风格来解决它?

IIUC, you just need to provide a default value for get , otherwise the result is None . IIUC,你只需要为get提供一个默认值,否则结果是None This can be done using a lambda function, for example:这可以使用 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)

Output输出

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

For:为了:

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

Output输出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM