当python中一行中有多个最大值时,在2-dim向量的每行中查找最大值



我正在寻找一种方法,在二维向量的每一行中找到最大值,并将其索引保存在另一个向量中。我知道我可以用这个代码做到这一点:

max_index = np.argmax(vec, axis=1)

现在我的问题是,当一行有多个最大值时,它会取它的第一个索引

vec = [[1, 0 ,1],
[1, 2 ,3],
[0, 5 ,5]]

因此,当一行中有多个最大值时,我想用-1代替最大值的索引。最后,max_index应该是这样的。

max_index = [-1, 2, -1]

提前感谢

技巧:从左到右取argmax,检查它们是否一致:

L = np.argmax(vec,1)
R = np.argmax(vec[:,::-1],1)
np.where(L+R==len(vec[0])-1,L,-1)
# array([-1,  2, -1])

如果您最初的问题是找到多个最大值的最后一个索引,那么您可以遵循以下方法

方法#1

np.argmax((vec.max(axis=1)[...,None] == vec).cumsum(axis=1), axis=1)

当一行中有重复的最大值时,将-1作为最后一个索引,将无法为类似[[1,1,0]]的行提供正确的索引。

CCD_ 2给出了每一行的最大值。

CCD_ 3将其转换为2D阵列。

CCD_ 4将每一行中的每个元素与每一行的最大值进行比较。

CCD_ 5产生累积和,其CCD_。

案例1:vec = [[1, 0 ,1], [1, 2 ,3], [0, 5 ,5]],结果为:[2,2,2]

案例2:vec = [[1, 1 ,0], [1, 2 ,3], [0, 5 ,5]],结果为:[1,2,2]

方法#2

R = np.argmax(vec[:,::-1],1) # Get the index of max from right side
result = vec.shape[1]-1-R 

这里我反转列,然后取argmax。在那之后,我正在进行调整以获得正确的索引

也许这可以解决您的问题:

# Creating a copy of vec
vec_without_max = np.copy(vec);
# Remove the max values found before from the new copy
for i in range(np.shape(vec)[0]):
vec_without_max[i][max_index[i]] = np.iinfo(vec_without_max[i][max_index[i]].dtype).min
# Find the max values on the copy array without the max values of vec
max_index_again = np.argmax(vec_without_max, axis=1)
# Compare the two arrays, if we have the same max value we set the max_index equals to -1
for i in range(np.shape(vec)[0]):
if vec[i][max_index[i]] == vec[i][max_index_again[i]]:
max_index[i] = -1

此脚本返回

max_index = [-1, 2, -1]

对于您发布的示例,但它应该适用于任何维度的数组。

最新更新