简体   繁体   中英

How to get the first smallest 5 values in a python Ndarray and get their position in the ndarray

我仍然无法弄清楚如何用更少的代码以最好的方式做到这一点,我有一个名为 X 的 Ndarray: array([0.5 , 2 , 3.2 , 0.16 , 3.3 , 10 , 12 , 2.5 , 10 , 1.2 ])我想以某种方式获得最小的 5 个值,它们在 X 中的位置是我想要的( 0.5 , 0.16 , 1.2, 2 ,2.5 ),并知道它们是 ndarray X 中的第一个和第四个、第 10 个和第二个第 8 个值(实际上是矩阵中一行的值,我想知道最小的位置 5 ) 谢谢!

You can use ndarray.argpartition :

X = np.array([0.5 , 2 , 3.2 , 0.16 , 3.3 , 10 , 12 , 2.5 , 10 , 1.2 ])

n = 5
arg = X.argpartition(range(n))[:n]

print(arg)
# [3 0 9 1 7]

print(X[arg])
# [0.16 0.5  1.2  2.   2.5 ]

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