1

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 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. How is this achieved elegantly for the y axis? axis=0 seems to infer the first column however axis=1 doesn't do the trick the second. what am I missing?
use np.argsort(x.reshape(-1,2), axis=0)[:k][:,1] explained the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.