首页 > 解决方案 > 使用 numpy 中的查找值进行数组操作

问题描述

lookup = np.array([60, 40, 50, 70, 90])

a = np.array([1, 2, 1, 4, 3, 2, 4, 9, 1])
b = np.array([2, 1, 2, 3, 3, 4, 9, 2, 1])
c = np.array([4, 2, 1, 4, 4, 1, 4, 4, 9])

以下数组值对应于以下查找值:

1 --> 60
2 --> 40
3 --> 50
4 --> 70
9 --> 90

这是我必须做的

array       1st column elements             lookup value

a            1        -->                   60
b            2        -->                   40
c            4        -->                   70

最大值为 70。

因此,结果的第一个元素是 4。

这边走,

预期结果 = array([4, 1, ...., 9])

解决此类问题的更好方法是什么?

标签: numpy

解决方案


您在这里有自定义索引,因此您需要设置一个字典来用查找值替换您的自定义索引,如下所示:

index_map = { 1: 60, 2: 40, 3: 50, 4: 70, 9: 90 }

lookup然后,我们使用以下索引的实际值创建一个临时 NumPy 数组d

temp = np.array([index_map[int(x)] for x in np.nditer(d)]).reshape(d.shape)

因此,我们可以在您之前的问题(选项 1)中重新使用此有效答案:

rows = temp.argmax(0)
print(d[rows, np.arange(d.shape[1])])

输出:

[4 1 1 4 4 4 9 9 9]

推荐阅读