如何在python中创建带有负索引/输入的查找表?

2024-04-29 09:35:34 发布

您现在位置: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的转换。你知道吗

我现在唯一能想到的就是做一个dict并迭代输入矩阵的所有元素。但那会很慢。如何有效地做到这一点?你知道吗


Tags: ofimportnumpy元素示例asnp矩阵
2条回答

另一种直观的方式:

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

我们可以用^{}-

In [43]: out[np.searchsorted(ind,a)]
Out[43]: 
array([[9, 8, 7],
       [6, 5, 4],
       [3, 2, 1]])

对于ind不一定排序的一般情况,我们需要使用sorterarg-

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

相关问题 更多 >