简体   繁体   English

从 numpy ndarray 索引多个最小值

[英]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?如何找到 K 个最小 X 值点的索引? eg for the below data with k=3 , the output should be something like [5,4,3]例如,对于以下k=3的数据,output 应该类似于[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由于您的数据不是nx2形状,因此首先对其进行整形并使用argsort获取排序索引和索引前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 x.reshape(-1,2) :重塑为n X 2
  • np.argsort(x.reshape(-1,2), axis=0) : Sort at columns; np.argsort(x.reshape(-1,2), axis=0) :按列排序; so both x's and y's are sorted independently所以x'sy's
  • np.argsort(x.reshape(-1,2), axis=0)[:k] : Get the top k idx np.argsort(x.reshape(-1,2), axis=0)[:k] : 获取前k个idx
  • np.argsort(x.reshape(-1,2), axis=0)[:k][:,0] : Get the idx of x's np.argsort(x.reshape(-1,2), axis=0)[:k][:,0] :获取x的idx

To do the same on y's are you need to do is index the idx of y s` ie.要在y's做同样的事情,你需要做的是索引of y s` 的 idx 即。

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

Output: Output:

array([5, 4, 3])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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