1

I have a 2D numpy array "bigrams" of shape (851, 851) with float values inside. I want to get the top ten values from this array and I want their coordinates.

I know that np.amax(bigrams) can return the single highest value, so that's basically what I want but then for the top ten.

As a numpy-noob, I wrote some code using a loop to get the top values per row and then using np.where() to get the coordinates, but i feel there must be a smarter way to solve this..

1
  • Could you post a small array and the expected output? Commented May 28, 2020 at 16:10

1 Answer 1

1

You can flatten and use argsort.

idxs = np.argsort(bigrams.ravel())[-10:]
rows, cols = idxs//851, idxs%851
print(bigrams[rows,cols])

An alternative would be to do a partial sorting with argpartition.

partition = np.argpartition(bigrams.ravel(),-10)[-10:]
max_ten = bigrams[partition//851,partition%851]

You will get the top ten values and their coordinates, but they won't be sorted. You can sort this smaller array of ten values later if you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is what I needed. I found you can also use np.unravel_index() to get back to the original 2D array's coordinates. That feels a bit more descriptive to me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.