i can't still figure out how to do this the best possible way with less code, i have a Ndarray called X : array([0.5 , 2 , 3.2 , 0.16 , 3.3 , 10 , 12 , 2.5 , 10 , 1.2 ]) and i want somehow to get the smallest 5 values with their position in X as in i want ( 0.5 , 0.16 , 1.2, 2 ,2.5 ) and to know that they are the first and fourth and 10th and second 8th in the ndarray X ( the are actually the the values of a row in a matrix and i want to know the position of the smallest 5 ) thank you!
Asked
Active
Viewed 80 times
-1
-
Does this answer your question? [Find the index of the k smallest values of a numpy array](https://stackoverflow.com/questions/34226400/find-the-index-of-the-k-smallest-values-of-a-numpy-array) – AMC Jan 16 '20 at 20:58
1 Answers
2
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 ]

yatu
- 86,083
- 12
- 84
- 139