我正在尝试从 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
时相关行的效率(list comp,reshape
,ndarrays
) :
np.array([meanings[f] for f in flags.flatten()]).reshape(flags.shape)
有没有更好/更有效的方法来执行这样的映射?
最佳答案
花哨的索引是 numpythonic 的做法:
mapped = meanings[flags]
或通常更快的等价物:
mapped = np.take(meanings, flags)
关于python - 使用字符串含义列表从 int 'flags' 的 ndarray 创建字符串 ndarray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17682738/