返回非平坦指数的numpy数组的Argmax

And*_*ler 73 python numpy multidimensional-array

我正在尝试获取Numpy数组中最大元素的索引.这可以使用numpy.argmax.我的问题是,我想找到整个数组中最大的元素并获得它的索引.

numpy.argmax 可以沿着一个轴应用,这不是我想要的,也可以应用在扁平数组上,这是我想要的.

我的问题是当我想要多维索引时,使用numpy.argmaxwith axis=None返回平面索引.

我可以divmod用来得到一个非平坦的索引,但这感觉很难看.有没有更好的方法呢?

Sve*_*ach 131

您可以使用numpy.unravel_index()以下结果numpy.argmax():

>>> a = numpy.random.random((10, 10))
>>> numpy.unravel_index(a.argmax(), a.shape)
(6, 7)
>>> a[6, 7] == a.max()
True
Run Code Online (Sandbox Code Playgroud)


eum*_*iro 16

np.where(a==a.max())
Run Code Online (Sandbox Code Playgroud)

返回最大元素的坐标,但必须解析数组两次.

>>> a = np.array(((3,4,5),(0,1,2)))
>>> np.where(a==a.max())
(array([0]), array([2]))
Run Code Online (Sandbox Code Playgroud)

与之相比argmax,这会返回所有元素的坐标等于最大值.argmax只返回其中一个(np.ones(5).argmax()返回0).

  • 这将迭代数组三次,而不是两次.一次找到最大值,第二次构建`==`的结果,第三次从该结果中提取'True`值.请注意,可能有多个项目等于最大值. (8认同)