我有一个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更多推荐
如何使用字典来翻译/替换数组的元素?
发布评论