如何在 python 中用负值 indices/inputs 查找 table?

How to make a look up table with negative indices/inputs in python?

我有一组输入矩阵 A,其中可能包含负元素。我还有一组从 intint 的映射,我希望将其有效地应用于 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]])

对不起,如果我不能准确地说出来。 不需要有一个函数来控制从 indout 的转换。

我现在唯一能想到的就是生成命令并遍历输入矩阵的所有元素。但那会很慢。如何有效地做到这一点?

我们可以使用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] returns ind 中值 a[x,y] 所在的索引。

>>> 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]])
>>>