Python 获取多维numpy数组中最大项的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3584243/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:49:47  来源:igfitidea点击:

Get the position of the biggest item in a multi-dimensional numpy array

pythonarraysindexingnumpy

提问by kame

How can I get get the position of the biggest item in a multi-dimensional numpy array?

如何获得多维numpy数组中最大项目的位置?

采纳答案by Manoj Govindan

The argmax()method should help.

argmax()方法应该有所帮助。

Update

更新

(After reading comment) I believe the argmax()method would work for multi dimensional arrays as well. The linked documentation gives an example of this:

(阅读评论后)我相信该argmax()方法也适用于多维数组。链接的文档给出了一个例子:

>>> a = array([[10,50,30],[60,20,40]])
>>> maxindex = a.argmax()
>>> maxindex
3

Update 2

更新 2

(Thanks to KennyTM's comment) You can use unravel_index(a.argmax(), a.shape)to get the index as a tuple:

(感谢KennyTM的评论)您可以使用unravel_index(a.argmax(), a.shape)将索引作为元组获取:

>>> from numpy import unravel_index
>>> unravel_index(a.argmax(), a.shape)
(1, 0)

回答by otterb

(edit) I was referring to an old answer which had been deleted. And the accepted answer came after mine. I agree that argmaxis better than my answer.

(编辑)我指的是一个已删除的旧答案。接受的答案是在我之后。我同意这argmax比我的答案更好。

Wouldn't it be more readable/intuitive to do like this?

这样做不是更易读/更直观吗?

numpy.nonzero(a.max() == a)
(array([1]), array([0]))

Or,

或者,

numpy.argwhere(a.max() == a)

回答by iFederx

You can simply write a function (that works only in 2d):

您可以简单地编写一个函数(仅适用于 2d):

def argmax_2d(matrix):
    maxN = np.argmax(matrix)
    (xD,yD) = matrix.shape
    if maxN >= xD:
        x = maxN//xD
        y = maxN % xD
    else:
        y = maxN
        x = 0
    return (x,y)