沿轴的 Numpy 最大值

标签 numpy

我在这里错过了什么吗?我希望以下代码段中的 np.max 会返回 [0, 4] ...

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

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

感谢您的指点。

最佳答案

看起来您想要包含最大值的行,对吗?
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])

关于沿轴的 Numpy 最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41913449/

相关文章:

python - numpy数组的缓冲区分区

python - 勒让德多项式导数

python - 溢出错误 : cannot convert float infinity to integer

python - 抑制可忽略不计的复杂 numpy 特征值?

python - 需要帮助解决 Raspberry Pi 上 matplotlib 的性能问题

python - OpenCV 和 Python : quickly superimpose mask over image without overflow

python - numpy:在 true_divide 中遇到无效值

python-3.x - Matplotlib FuncAnimation 没有动画线图

python - 高效使用 numpy_indexed 输出

python - 查询基于索引和数据列的 Pandas 数据框