Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may use 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:

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

Updated:

As OP's times show, and much clearer that argmin is desired (no duplicated mins etc.), one way I think may slightly improve OP's original approach is to use 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...