Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retain the index of an array element after flattening and sorting into descending order using sort()

I have a 2D array of integers. I need to find the largest value within the entire array along with its index.

Currently I am flattening the array and then using the sort() function to find the highest value. The problem is my array has multiples (12,000,000+ elements) so after sorting I don’t know how to recover the index.

maskingarray = Data.copy()
flatmask = maskingarray.flatten()
flatmask.sort()

This code allows me to access the element with the highest value but I need but the position in the 2D array also.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a better method which allows me to retain the indexing of the original array? Preferably just finding the largest value without having to flatten at all.

(For context: I need the indexing because I am doing aperture photometry, essentially finding a galaxy with the highest luminosity and looking at a radius around it)

Thanks for any help

>Solution :

This is similar to prior questions, and I think the answer is in [this one][1]
https://stackoverflow.com/questions/5469286/how-to-get-the-index-of-a-maximum-element-in-a-numpy-array-along-one-axis

There is an elegant solution using Numpy [argmax][1]
[1]: https://numpy.org/doc/stable/reference/generated/numpy.argmax.html

an argmax solution:

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> [i,j]
[1,0]
>>> a[i,j]
4
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading