Python Numpy:获取二维数组最小值的列和行索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30180241/
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-19 08:03:17  来源:igfitidea点击:

Numpy: get the column and row index of the minimum value of a 2D array

pythonarraysnumpy

提问by N. H.

For example,

例如,

x = array([[1,2,3],[3,2,5],[9,0,2]])
some_func(x) gives (2,1)

I know one can do it by a custom function:

我知道可以通过自定义函数来做到这一点:

def find_min_idx(x):
    k = x.argmin()
    ncol = x.shape[1]
    return k/ncol, k%ncol

However, I am wondering if there's a numpy built-in function that does this faster.

但是,我想知道是否有一个 numpy 内置函数可以更快地执行此操作。

Thanks.

谢谢。

EDIT: thanks for the answers. I tested their speeds as follows:

编辑:感谢您的回答。我测试了它们的速度如下:

%timeit np.unravel_index(x.argmin(), x.shape)
#100000 loops, best of 3: 4.67 μs per loop

%timeit np.where(x==x.min())
#100000 loops, best of 3: 12.7 μs per loop

%timeit find_min_idx(x) # this is using the custom function above
#100000 loops, best of 3: 2.44 μs per loop

Seems the custom function is actually faster than unravel_index() and where(). unravel_index() does similar things as the custom function plus the overhead of checking extra arguments. where() is capable of returning multiple indices but is significantly slower for my purpose. Perhaps pure python code is not that slow for doing just two simple arithmetic and the custom function approach is as fast as one can get.

似乎自定义函数实际上比 unravel_index() 和 where() 快。unravel_index() 做与自定义函数类似的事情,加上检查额外参数的开销。where() 能够返回多个索引,但对于我的目的来说要慢得多。也许纯 python 代码只执行两个简单的算术运算并不会那么慢,而自定义函数方法则尽可能快。

采纳答案by Anzel

You may use np.where:

您可以使用np.where

In [9]: np.where(x == np.min(x))
Out[9]: (array([2]), array([1]))

Also as @senderle mentioned in comment, to get values in an array, you can use np.argwhere:

同样如评论中提到的@senderle,要获取数组中的值,您可以使用np.argwhere

In [21]: np.argwhere(x == np.min(x))
Out[21]: array([[2, 1]])

Updated:

更新:

As OP's times show, and much clearer that argminis desired (no duplicated mins etc.), one way I think may slightly improve OP's original approach is to use divmod:

正如 OP 的时间所显示的那样,并且更清晰argmin(没有重复的分钟等),我认为可以稍微改进 OP 原始方法的一种方法是使用divmod

divmod(x.argmin(), x.shape[1])

Timed them and you will find that extra bits of speed, not much but still an improvement.

给它们计时,你会发现额外的速度,虽然不多,但仍然是一个改进。

%timeit find_min_idx(x)
1000000 loops, best of 3: 1.1 μs per loop

%timeit divmod(x.argmin(), x.shape[1])
1000000 loops, best of 3: 1.04 μs per loop

If you are really concerned about performance, you may take a look at cython.

如果你真的很关心性能,你可以看看cython

回答by Padraic Cunningham

You can use np.unravel_index

您可以使用np.unravel_index

print(np.unravel_index(x.argmin(), x.shape))
(2, 1)