【问题标题】:How to get the maximum value and the position from each row of a matrix [duplicate]如何从矩阵的每一行中获取最大值和位置[重复]
【发布时间】:2018-06-10 08:11:17
【问题描述】:

假设我有一个这样的矩阵A=np.array([[1,2,3],[5,2,6],[7,1,5]])

然后,我想从每一行中选择最大值和位置。

结果应该是 Value=[3,6,7], Position=[2,2,0]。

在Matlab中,代码[Value,Position]=max(A);可以计算出正确答案

但是我需要把它改成 Python 代码。

我曾经试过这样的代码

Value=np.max(A, axis=1)
Position=np.where(A==np.max(A,axis=1)) 

Result:
Value=array([3, 6, 7])
Position=(array([], dtype=int32), array([], dtype=int32))

最大值是正确的,但位置是错误的。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    从argmax 开始,并使用结果将您的索引编入您的数组。

    idx = A.argmax(axis=1)
    val = A[np.arange(len(A)), idx]
    

    idx
    array([2, 2, 0])    
    
    val
    array([3, 6, 7])
    

    【讨论】:

    • 非常感谢^_^
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多