我有一组输入矩阵,A
可能有负元素。我还有一组从int
到int
的映射,我希望有效地应用于A
。 例:
import numpy as np
ind = np.array([-9, -8, -7, -6, -5, -4, -3, -2, -1])
out = np.array([ 1, 2, 3, 4, 5, 6, 7, 8, 9])
# i-th element of ind should return i-th element of out
a = np.array([[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]])
# print(a)
# array([[-1, -2, -3],
# [-4, -5, -6],
# [-7, -8, -9]])
# i want output as
# array([[ 9, 8, 7],
# [ 6, 5, 4],
# [ 3, 2, 1]])
对不起,如果我不能准确地说出来。 不需要管理从ind
到out
的转换的函数。
我现在唯一能想到的就是制定字典并迭代输入矩阵的所有元素。但那会很慢。如何有效地做到这一点?
我们可以使用np.searchsorted
-
In [43]: out[np.searchsorted(ind,a)]
Out[43]:
array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
对于ind
不一定排序的通用情况,我们需要使用sorter
arg -
In [44]: sidx = ind.argsort()
In [45]: out[sidx[np.searchsorted(ind,a,sorter=sidx)]]
Out[45]:
array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
另一种直观的方式:
np.where(ind==a[x, y])[0][0]
返回a[x,y]
所在的值所在的索引ind
。
>>> result = np.zeros(a.shape, dtype=np.int)
>>> for x in range(0, len(a[0])): #rows
... for y in range(0, len(a[1])): #columns
... indexInOut = np.where(ind==a[x, y])[0][0]
... result[x,y] = out[indexInOut]
...
>>> result
array([[9, 8, 7],
[6, 5, 4],
[3, 2, 1]])
>>>