猿问

迭代 numpy 数组以在离开行索引的子数组中找到最大值

我想找到沿轴 = 0 的二维数组的最大值,我不想在行索引处包含该值。我对这个解决方案不满意,因为我需要在一百万行上运行它,而且我不想在这里使用 for 循环。我试过numpy.argmax但它计算行的最大值,包括行索引处的值。


我的二维数组


Arry=([[1,   0.5, 0.3,   0,    0.2],

       [0,   1,   0.2,   0.8,  0],

       [0,   1,   1,     0.3,  0],

       [0,   0,   0,     1,    0]])

预期产出


[1, 3, 1]

第一行 [1, 0.5, 0.3, 0, 0.2] 在索引 1 处具有最大值,即 0.5,因为值 1 在行索引 0 处,同样在第二行中最大值为 0.8,即索引 3,第 4 行没有有任何最大值,因为都为零


我的代码


import numpy as np


for idx,subarry in enumerate(Arry):

    newlist=np.delete(subarry, idx)

    idx_min=min(np.where(subarry==np.max(newlist))[0])

    if idx_min != 0: min_elem_idx.append(idx_min)


print(min_elem_idx)

[1, 3, 1]

我正在寻找一种 Pythonic 的方式来实现这一点而不使用 for 循环


森林海
浏览 193回答 1
1回答

不负相思意

这应该可以解决问题:a = np.array([[1,   0.5, 0.3,   0,    0.2],              [0,   1,   0.2,   0.8,  0],              [0,   1,   1,     0.3,  0],              [0,   0,   0,     1,    0]])# Create an array of ones the same size as ab = np.ones_like(a)# Fill the diagonal of b with NaNnp.fill_diagonal(b, np.nan)# Multiply the arrays in order to remove the index column from the maxc = a*b# Find the index of the max value of every row (excluding the index value)np.nanargmax(c, axis=1)输出:array([1, 3, 1, 0])为了过滤掉每个值都为零的情况(因此“没有最大值”,正如您定义的那样),您必须做一些额外的工作。
随时随地看视频慕课网APP

相关分类

Python
我要回答