例如,
x = array([[1,2,3],[3,2,5],[9,0,2]])
some_func(x) gives (2,1)
Run Code Online (Sandbox Code Playgroud)
我知道可以通过自定义函数来实现:
def find_min_idx(x):
k = x.argmin()
ncol = x.shape[1]
return k/ncol, k%ncol
Run Code Online (Sandbox Code Playgroud)
但是,我想知道是否有一个numpy内置函数可以更快地执行此操作.
谢谢.
编辑:谢谢你的答案.我测试了它们的速度如下:
%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
Run Code Online (Sandbox Code Playgroud)
似乎自定义函数实际上比unravel_index()和where()更快.unravel_index()执行与自定义函数类似的操作以及检查额外参数的开销.where()能够返回多个索引,但是对于我的目的而言要慢得多.也许纯粹的python代码并不是那么简单,只做两个简单的算术,自定义函数方法就像人们可以获得的那样快.