我试图从一个整数’标志’的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')
使用字符串列表作为’flags’到’含义’的映射:
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')
这是有效的,但我关注处理大型ndarray时相关行的效率(list comp,flatten,reshape):
np.array([meanings[f] for f in flags.flatten()]).reshape(flags.shape)
是否有更好/更有效的方式来执行这样的映射?
解决方法:
花哨的索引是这样做的numpythonic方式:
mapped = meanings[flags]
或通常更快的等价物:
mapped = np.take(meanings, flags)