Python 如何返回numpy中的所有最小索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18582178/
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
How to return all the minimum indices in numpy
提问by Salvador Dali
I am a little bit confused reading the documentation of argmin function in numpy. It looks like it should do the job:
阅读numpy中argmin 函数的文档时,我有点困惑。看起来它应该可以完成这项工作:
Reading this
读这个
Return the indices of the minimum values along an axis.
返回沿轴的最小值的索引。
I might assume that
我可能认为
np.argmin([5, 3, 2, 1, 1, 1, 6, 1])
will return an array of all indices: which will be [3, 4, 5, 7]
将返回所有索引的数组:这将是 [3, 4, 5, 7]
But instead of this it returns only 3
. Where is the catch, or what should I do to get my result?
但它只返回3
. 问题在哪里,或者我应该怎么做才能得到结果?
采纳答案by user2357112 supports Monica
That documentation makes more sense when you think about multidimensional arrays.
当您考虑多维数组时,该文档更有意义。
>>> x = numpy.array([[0, 1],
... [3, 2]])
>>> x.argmin(axis=0)
array([0, 0])
>>> x.argmin(axis=1)
array([0, 1])
With an axis specified, argmin
takes one-dimensional subarrays along the given axis and returns the first index of each subarray's minimum value. It doesn't return all indices of a single minimum value.
指定轴后,argmin
沿给定轴获取一维子数组并返回每个子数组最小值的第一个索引。它不会返回单个最小值的所有索引。
To get all indices of the minimum value, you could do
要获得最小值的所有索引,您可以执行
numpy.where(x == x.min())
回答by nneonneo
See the documentation for numpy.argmax
(which is referred to by the docs for numpy.argmin
):
请参阅文档numpy.argmax
(由 文档引用numpy.argmin
):
In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence are returned.
如果最大值出现多次,则返回与第一次出现对应的索引。
The phrasing of the documentation ("indices" instead of "index") refers to the multidimensional case when axis
is provided.
文档的措辞(“索引”而不是“索引”)是指提供时的多维情况axis
。
So, you can't do it with np.argmin
. Instead, this will work:
所以,你不能用np.argmin
. 相反,这将起作用:
np.where(arr == arr.min())
回答by grofte
Assuming that you want the indices of a list, not a numpy array, try
假设您想要列表的索引,而不是 numpy 数组,请尝试
my_list = [5, 3, 2, 1, 1, 1, 6, 1]
np.where(my_list == min(my_list))[0]
The index [0] is because numpy returns a tuple of your answer and nothing (answer as a numpy array). Don't ask me why.
索引 [0] 是因为 numpy 返回了你的答案的元组,什么都没有(作为 numpy 数组的答案)。不要问我为什么。
回答by Luksurious
I would like to quickly add that as user grofte mentioned, np.where
returns a tuple and it states that it is a shorthand for nonzero
which has a corresponding method flatnonzero
which returns an array directly.
我想快速补充一下,正如用户 grofte 提到的,np.where
返回一个元组,它声明它是一个速记,nonzero
它有一个flatnonzero
直接返回数组的相应方法。
So, the cleanest version seems to be
所以,最干净的版本似乎是
my_list = np.array([5, 3, 2, 1, 1, 1, 6, 1])
np.flatnonzero(my_list == my_list.min())
=> array([3, 4, 5, 7])