简体   繁体   中英

indexing multiple minimum values from a numpy ndarray

I have a set of coordinates in the below data structure. How do I find the indices for the K minimal X value points? eg 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)

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 y s` ie.

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

Output:

array([5, 4, 3])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM