【问题标题】:Numpy max along axis沿轴的 Numpy 最大值
【发布时间】:2017-01-28 18:43:22
【问题描述】:

我在这里遗漏了什么吗?我希望以下 sn-p 中的 np.max 会返回 [0, 4]...

>>> a
   array([[1, 2],
          [0, 4]])

>>> np.max(a, axis=0)
   array([1, 4])

感谢您的任何指点。

【问题讨论】:

    标签: numpy


    【解决方案1】:

    看起来你想要包含最大值的行,对吧?

    max(axis=0) 分别返回 [1,0] 和 [2,4] 的最大值。

    argmax 没有轴参数在整个数组中找到最大值 - 以扁平形式。要将索引转换为行号,我们必须使用unravel_index

    In [464]: a.argmax()
    Out[464]: 3
    In [465]: np.unravel_index(3,(2,2))
    Out[465]: (1, 1)
    In [466]: a[1,:]
    Out[466]: array([0, 4])
    

    或者在一个表达式中:

    In [467]: a[np.unravel_index(a.argmax(), a.shape)[0], :]
    Out[467]: array([0, 4])
    

    从答案的长度可以看出,这不是沿/超过轴的最大值的通常定义。

    Sum along axis in numpy array 可能会更深入地了解“沿轴”的含义。相同的定义适用于 summeanmax 操作。

    ====================

    要选择norm 最大的行,首先计算范数。 norm 以同样的方式使用axis 参数。

    In [537]: np.linalg.norm(a,axis=1)
    Out[537]: array([ 2.23606798,  4.        ])
    In [538]: np.argmax(_)
    Out[538]: 1
    In [539]: a[_,:]
    Out[539]: array([0, 4])
    

    【讨论】:

    • 啊...我在想 max( ) 返回最大的行/列(以元素的平方和来衡量)。谢谢。
    • 我添加了一个使用norm 对行进行排名的示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2017-03-27
    • 2012-01-29
    • 2019-06-25
    • 1970-01-01
    相关资源
    最近更新 更多