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 1 can custom function:

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

however, wondering if there's numpy built-in function faster.

thanks.

edit: answers. tested speeds 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) # using custom function above #100000 loops, best of 3: 2.44 µs per loop 

seems custom function faster unravel_index() , where(). unravel_index() similar things custom function plus overhead of checking arguments. where() capable of returning multiple indices slower purpose. perhaps pure python code not slow doing 2 simple arithmetic , custom function approach fast 1 can get.

you may use np.where:

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

also @senderle mentioned in comment, values in array, can use np.argwhere:

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

updated:

as op's times show, , clearer argmin desired (no duplicated mins etc.), 1 way think may improve op's original approach use divmod:

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

timed them , find bits of speed, not still 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 concerned performance, may take @ cython.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -