1

I need a function that returns the index (row and column) of the N highest element from a matrix/list of numpy array.

Suppose that I have the following matrix:

a = [[4,2,3], 
     [5,0,3]]

I would like to get a list of the indexes (row,column) of the N highest elements. For example, if I want the index of the 4 highest element, the function should return

[(1,0), (0,0), (0,2), (1,2)]

I have tried implementing this as following, but it returns a list of (value, row number), which is not want I need

for i, sub_list in enumerate(a):
    max_list.append((max(sub_list), i))
3
  • I think you have an error in your output. (1, 2) should be included instead of (0, 1), since 3 > 2 Commented Feb 14, 2020 at 14:29
  • Yes you are right. I have modified the question, thanks! Commented Feb 14, 2020 at 14:36
  • 1
    Does this answer your question? How do I get indices of N maximum values in a NumPy array? There are solutions for 2D arrays as well. Commented Feb 14, 2020 at 15:02

1 Answer 1

4

I would flatten, argsort, and unravel_index


f = a.ravel().argsort()
[*zip(*np.unravel_index(f[-n:], a.shape))]

[(0, 2), (1, 2), (0, 0), (1, 0)]

As yatu points out, if you have a larger array, and a small-ish n, you can replace argsort with np.argpartition(a.ravel(), -n).

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.