indexing multiple minimum values from a numpy ndarray

Viewed 78

I have a set of coordinates in the below data structure. How do I find the indices for the K minimal X value points? e.g. for the below data with k=3, the output should be something like [5,4,3]

array([[[463, 445]],
       [[461, 447]],
       [[461, 448]],
       [[ 42,   2]],
       [[ 41,   1]],
       [[ 40, 100]]], dtype=int32)
1 Answers

Since your data is not in nx2 shape, reshape it first and use argsort to get the sorted indices and index first k

x = np.array(
    [[[463, 445]],
     [[461, 447]],
     [[461, 448]],
     [[ 42,   2]],
     [[ 41,   1]],
     [[ 40, 100]]])

k = 3
print (np.argsort(x.reshape(-1,2), axis=0)[:k][:,0])

Ouput:

[5 4 3]
  • x.reshape(-1,2) : Reshape into n X 2
  • np.argsort(x.reshape(-1,2), axis=0) : Sort at columns; so both x's and y's are sorted independently
  • np.argsort(x.reshape(-1,2), axis=0)[:k]: Get the top k idx
  • np.argsort(x.reshape(-1,2), axis=0)[:k][:,0]: Get the idx of x's

To do the same on y's are you need to do is index the idx of ys` ie.

print (np.argsort(x.reshape(-1,2), axis=0)[:k][:,1])

Output:

array([5, 4, 3])
Related