numpy的2D数组最大/最大 [英] numpy 2d array max/argmax

查看:128
本文介绍了numpy的2D数组最大/最大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy矩阵:

I have a numpy matrix:

>>> A = np.matrix('1 2 3; 5 1 6; 9 4 2')
>>> A
matrix([[1, 2, 3],
        [5, 1, 6],
        [9, 4, 2]])

我想获取每行最大值的索引以及值本身. 我可以使用A.argmax(axis = 1)获得最大值的索引,在这种情况下,我将得到:

I'd like to get the index of the maximum value in each row along with the value itself. I can get the indices for the maximums using A.argmax(axis=1), in that case I would get:

>>> indices = A.argmax(axis=1)
>>> indices
matrix([[2],
        [2],
        [0]])

如何使用索引"数组获取矩阵中每一行的最大值数组?有什么方法可以更有效地完成一项操作?是否有一个函数可以返回值以及它们的行和列坐标?

How can I use the 'indices' array to get an array of maximum values for each row in the matrix? Is there any way I can do this more efficiently or in one operation? Is there a function that would return the values along with their row and column coordinates?

推荐答案

您可以在第一个维度上使用索引np.arange(len(A))进行索引(因为您希望每行有一个值),并且索引(压缩的)对应到第二维上每一行的索引:

You can fancy-index using the indices np.arange(len(A)) on first dimension (since you want a value per row), and your indices (squeezed), which correspond to the index on each row, on the second dimension:

A[np.arange(len(A)) , indices.squeeze()]
=> matrix([[3, 6, 9]])

这篇关于numpy的2D数组最大/最大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆