如何使用字典来翻译/替换数组的元素? [英] How to use a dictionary to translate/replace elements of an array?
问题描述
我有一个numpy数组,其中包含数百个大写字母的元素,没有特定顺序
I have a numpy array, which has hundreds of elements which are capital letters, in no particular order
import numpy as np
abc_array = np.array(['B', 'D', 'A', 'F', 'H', 'I', 'Z', 'J', ...])
此numpy.ndarray
中的每个元素都是一个numpy.string_
.
Each element in this numpy.ndarray
is a numpy.string_
.
我还有一个翻译词典",其中包含键/值对,以便大写字母对应于城市
I also have a "translation dictionary", with key/value pairs such that the capital letter corresponds to a city
transdict = {'A': 'Adelaide', 'B': 'Bombay', 'C': 'Cologne',...}
字典transdict
中只有26对,但是numpy数组中有数百个字母我必须翻译.
There are only 26 pairs in the dictionary transdict
, but there are hundreds of letters in the numpy array I must translate.
最有效的方法是什么?
What is the most efficient way to do this?
我已经考虑过使用numpy.core.defchararray.replace(a, old, new, count=None)[source]
,但这会返回ValueError
,因为numpy数组的大小与字典键/值的大小不同.
I have considered using numpy.core.defchararray.replace(a, old, new, count=None)[source]
but this returns a ValueError
, as the numpy array is a different size that the dictionary keys/values.
AttributeError: 'numpy.ndarray' object has no attribute 'translate'
推荐答案
这样做会吗?有时,纯Python是处理此类问题的一种好方法.下面将构建翻译列表(轻松转换回numpy数组)和合并的输出.
Will this do? Sometimes, plain Python is a good, direct way to handle such things. The below builds a list of translations (easily converted back to a numpy array) and the joined output.
import numpy as np
abc_array = np.array(['B', 'D', 'A', 'F', 'H', 'I', 'Z', 'J'])
transdict = {'A': 'Adelaide',
'B': 'Bombay',
'C': 'Cologne',
'D': 'Dresden',
'E': 'Erlangen',
'F': 'Formosa',
'G': 'Gdansk',
'H': 'Hague',
'I': 'Inchon',
'J': 'Jakarta',
'Z': 'Zambia'
}
phoenetic = [transdict[letter] for letter in abc_array]
print ' '.join(phoenetic)
输出为:
Bombay Dresden Adelaide Formosa Hague Inchon Zambia Jakarta
这篇关于如何使用字典来翻译/替换数组的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!