我正在尝试从ndarray
整数“标志”开始:
array([[1, 3, 2],
[2, 0, 3],
[3, 2, 0],
[2, 0, 1]])
到一个ndarray
字符串:
array([['Banana', 'Celery', 'Carrot'],
['Carrot', 'Apple', 'Celery'],
['Celery', 'Carrot', 'Apple'],
['Carrot', 'Apple', 'Banana']],
dtype='|S6')
使用字符串列表作为“标志”到“含义”的映射:
meanings = ['Apple', 'Banana', 'Carrot', 'Celery']
我想出了以下几点:
>>> import numpy as np
>>> meanings = ['Apple', 'Banana', 'Carrot', 'Celery']
>>> flags = np.array([[1,3,2],[2,0,3],[3,2,0],[2,0,1]])
>>> flags
array([[1, 3, 2],
[2, 0, 3],
[3, 2, 0],
[2, 0, 1]])
>>> mapped = np.array([meanings[f] for f in flags.flatten()]).reshape(flags.shape)
>>> mapped
array([['Banana', 'Celery', 'Carrot'],
['Carrot', 'Apple', 'Celery'],
['Celery', 'Carrot', 'Apple'],
['Carrot', 'Apple', 'Banana']],
dtype='|S6')
这行得通,但我担心在处理大时相关行的效率(列表比较flatten
,,, ) :reshape
ndarrays
np.array([meanings[f] for f in flags.flatten()]).reshape(flags.shape)
有没有更好/更有效的方式来执行这样的映射?