Home > Mobile >  Find n argmins in 2d array
Find n argmins in 2d array

Time:11-08

I need to find n argmins in 2d array in python, how can I do that?

EXAMPLE:

a=np.array([[1, 5, 9], [2, 3, 10], [4, 11, 12]])
argmins = n_argmins(a, 5) # finding 5 argmins
print(argmins)

OUTPUT:

[[0 1]
 [0 2]
 [1 0]
 [1 1]
 [2 0]]

CodePudding user response:

You can try the following:

import numpy as np

a=np.array([[1, 5, 9], [2, 3, 10], [4, 11, 12]])
np.c_[np.unravel_index(a.ravel().argsort()[:5], a.shape)]

It gives:

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

CodePudding user response:

cast the data into a list but remember the original indexes. search for n min args in the list.

code:

def n_argmins(a, n)
  for i,inner in enumerate(a):
     for j,x in enumerate(inner):
         indexes[x] = [i,j]
         a_new.append(x)
  res = []
  for _ in range(n):
     res.append(indexes[min(a_new)])
     a_new.remove(min(a_new))
  return res

assuming all the list are sorted (as shown in the example) we can solve it in a better way. The solution is based on the idea that the first values in every inner list are already the min args of that list. So we just need to search on them. code:

n = 5
next_possible_mins = [0]*len(a)
indexes = [0]*len(a)
result = []
for i in range(len(a)):
    next_possible_mins[i] = a[i][0]
    indexes[i] = [0, i]

for i in range(n):
    index_min = next_possible_mins.index(min(next_possible_mins))
    result.append(indexes[index_min])
    indexes[index_min] = [indexes[index_min][0] 1, indexes[index_min][1]]
    next_possible_mins[index_min] = a[indexes[index_min][1]][indexes[index_min][0]]

print(result)
  • Related