-1

How to find the indexes of 10 highest numbers in a 14x14 numpy matrix efficiently? I want the output to be tuples of the indexes where the maximum numbers are located printed in the order of the highest number to the least. I tried using argsort but that only takes in one axis to sort against. This is not a duplicate because it is specifically asking for a 2d array and the answers of the other question only apply to a 1d array.

For example:

[[0,1,2],
 [3,4,5],
 [6,7,8]]

(2,2,8)
(1,2,7)
(0,2,6)
pr338
  • 8,730
  • 19
  • 52
  • 71

1 Answers1

2

You could flatten the array, do a sort and output the first 10. Then also tack on the original indices

new_list = []
for i, row in enumerate(matrix):
    for j, col in enumerate(row):
        new_list.append((col, (i,j)))

sorted_list = sorted(new_list, key=lambda x: x[0], reverse=True)
top_ten = sorted_list[:10]
for i in top_ten:
    print "Value: {0}, Index: {1}".format(i[0], i[1])
quikst3r
  • 1,783
  • 1
  • 10
  • 15