两个数组之间的数组索引

问题描述 投票:0回答:2

enter image description here

我有一个numpy数组和相应的查找值。从每一列数据中,我都应该获得相应查找的最大位置,并将该位置转换为数据结果。

我必须如图所示做。

图片说得比我的语言还好。

import numpy as np

data = np.array([[0, 2, 1, 4, 3, 2, 4, 4, 1],
                 [1, 1, 2, 0, 3, 4, 4, 2, 1],
                 [2, 2, 1, 4, 4, 1, 4, 4, 4]] )

print (data)

print ()

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

print (lookup)

print ()

我做了如下:

data = data.transpose(1,0)

lookup = lookup.transpose(1,0)

results = []       
for d in data:   
   matches = lookup[d].diagonal()
   print (matches)
   idx = np.argmax(matches, axis=0)
   res = d[idx]
   results.append(res)

print ()

print (results)  

有效。但是,还有更好的方法吗?

python numpy
2个回答
1
投票

您可以使用扁平化事实:

l = lookup.shape[1]
data1 = (data + [[0],[l], [2*l]]).copy()
matches = lookup.flatten()[data1.flatten()].reshape(data1.shape).T
results = data.T[:, np.argmax(matches, axis = 1)].diagonal()
print(matches)
print(results)

输出

[[60 90 90]
 [90 90 90]
 [90 80 40]
 [50 90 50]
 [60 90 50]
 [90 90 40]
 [50 90 50]
 [50 80 50]
 [90 90 50]]  # matches

[1 2 1 0 3 2 4 2 1]  #results

0
投票

我不确定我是否了解您,但是也许这正是您想要的?

data = data.T
lookup = lookup.T
cols = np.zeros_like(data) + np.array([0, 1, 2])
idx = np.argmax(lookup[data, cols], axis=1)
data[np.arange(data.shape[0]), idx]

0
投票

使用numpy's fancy indexing。使用它,您可以提供索引数组。参见示例:

data = np.arange(20)
data[[0, 1, 5, 10]]    # array([ 0,  1,  5, 10])

用于索引的数组也会广播。参见示例:

data = np.arange(20).reshape(5, 4)
i = np.array([0, 4])
j = np.array([0, 3])
data[i, j]                                 # array([ 0, 19])
i, j = i[:, np.newaxis], j[np.newaxis, ]
data[i, j]                                 # array([[ 0,  3], [16, 19]])

在您的情况下,matches等于matches[i, j] = lookup[i, data[i, j]]。使用花式索引,我们这样做:

i = np.arange(data.shape[-2])[:, np.newaxis]
matches = lookup[i, data]

最终结果应该是result[j] = data[i_max[j], j],其中i_max[j] = argmax_i(matches[i, j])表示为:

i_max = np.argmax(matches, axis=-2)
j = np.arange(data.shape[-1])
result = data[i_max, j]
© www.soinside.com 2019 - 2024. All rights reserved.