Python : how to locate the maximum of a array (ndim>1, and efficiently)

It sounds stupid, but I searched a long time to be able to find the position of the maximum of an array.

Find the maximum is really easy : myArray.max()

you might be tempted by searching the position of that maximum.

You may do it with loops, but then you have to write a function for each dimension : 1 loop for a flat array, 2 loops for a 2D array, etc…. And you wanted a optimized code : don’t even think about loops !

I found a tricky one : numpy.where locate you what you want in your array. So this code is nicely working. Remember this one, because you may use it with « myArray>100 » if you want the coordinates where the values are above 100

np.array(np.where(myArray==myArray.max())).T

But actually, searching a bit more in Numpy, i found the « argmax » function. I thought : it’s done ! Not completely. The function gives you the index of the flattened array. So you need this extra « unravel_index » tricks :

np.unravel_index(myArray.argmax(),myArray.shape)

Guess what : the « unravel_index(argmax » solution is 10 times faster than the where(a==a.max())…

 

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *