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
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