返回非平面索引的 numpy 数组的 Argmax [英] Argmax of numpy array returning non-flat indices

查看:29
本文介绍了返回非平面索引的 numpy 数组的 Argmax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我可以使用 divmod 来获得非平面索引,但这感觉很难看.有没有更好的方法来做到这一点?

解决方案

你可以使用 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()真的

I'm trying to get the indices of the maximum element in a Numpy array. This can be done using numpy.argmax. My problem is, that I would like to find the biggest element in the whole array and get the indices of that.

numpy.argmax can be either applied along one axis, which is not what I want, or on the flattened array, which is kind of what I want.

My problem is that using numpy.argmax with axis=None returns the flat index when I want the multi-dimensional index.

I could use divmod to get a non-flat index but this feels ugly. Is there any better way of doing this?

解决方案

You could use numpy.unravel_index() on the result of numpy.argmax():

>>> a = numpy.random.random((10, 10))
>>> numpy.unravel_index(a.argmax(), a.shape)
(6, 7)
>>> a[6, 7] == a.max()
True

这篇关于返回非平面索引的 numpy 数组的 Argmax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆