-1

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.

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

3
  • 1
    Is Data a numpy array or a python list? Commented Dec 16, 2024 at 20:25
  • The data is a numpy array, currently trying to find the maximum and index then set that pixel to zero and repeat Commented Dec 16, 2024 at 20:28
  • 1
    Let us know what this array is. Better, yet, post a small working example that we can use as a basis for our answers. You have 12 million element? Knock that down to a dozen for the example. Commented Dec 16, 2024 at 20:29

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I had those lines within a getmax function but I wasn't implementing properly, thanks for your help
np, the solution that they pointed to on this question doesn't EXACTLY match what you were looking for as well, people can be nitpicky here, but dont let it discourage you from asking questions
Haha I see that now! Thanks for the advice

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.