为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

森林海 2021-12-09 14:41:38
我想找到沿轴 = 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])

为了过滤掉每个值都为零的情况(因此“没有最大值”,正如您定义的那样),您必须做一些额外的工作。


查看完整回答
反对 回复 2021-12-09
  • 1 回答
  • 0 关注
  • 192 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号