Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indicies or numpy array to tuple of integers?

I am trying to get a tuple that contains the indicies of the minimum value in an numpy array.

import numpy as np
a=np.array(([2,3,1],[5,4,6],[8,7,9]))
b=np.where(a==np.min(a))
print(b)

gives:

(array([0]),array([2]))

Attempting to map the result to a tuple:

c=map(tuple,b)
print(c)

gives:

[(0,), (2,)]

but what I want is:

(0,2)

Any suggestions other than np.where are perfectly acceptable. Thanks.

like image 996
Wes Avatar asked Jan 26 '26 17:01

Wes


2 Answers

The easiest way to get your desired result is

>>> np.unravel_index(a.argmin(), a.shape)
(0, 2)

The argmin() method finds the index of the minimum element in the flattened array in a single pass, and thus is more efficient than first finding the minimum and then using a linear search to find the index of the minimum.

As the second step, np.unravel_index() converts the scalar index into the flattened array back into an index tuple. Note that the entries of the index tuple have the type np.int64 rather than plain int.

like image 177
Sven Marnach Avatar answered Jan 28 '26 06:01

Sven Marnach


For a case when you would have multiple elements with the same min value, you might want to have a list of tuples. For such a case, you could use map after column-stacking the rows and columns info obtained from np.where, like so -

map(tuple,np.column_stack(np.where(a==np.min(a))))

Sample run -

In [67]: a
Out[67]: 
array([[2, 2, 0, 1, 0],
       [0, 2, 0, 0, 3],
       [1, 0, 1, 2, 1],
       [0, 3, 3, 3, 3]])

In [68]: map(tuple,np.column_stack(np.where(a==np.min(a))))
Out[68]: [(0, 2), (0, 4), (1, 0), (1, 2), (1, 3), (2, 1), (3, 0)]
like image 35
Divakar Avatar answered Jan 28 '26 08:01

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!