我想找到沿轴 = 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 npfor 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 循环
1 回答

不负相思意
TA贡献1777条经验 获得超10个赞
这应该可以解决问题:
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 a
b = np.ones_like(a)
# Fill the diagonal of b with NaN
np.fill_diagonal(b, np.nan)
# Multiply the arrays in order to remove the index column from the max
c = 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])
为了过滤掉每个值都为零的情况(因此“没有最大值”,正如您定义的那样),您必须做一些额外的工作。
添加回答
举报
0/150
提交
取消