I am currently trying to sort a numpy array, but i am running into a difficulty
The array that i want to sort is the following:
mat = np.array([0.05170475 0.07367926 0.05741241 0.34870369 0.19990381 0.26859608])
Now the difficult part here, is that i want to sort the array, but also keep the indexes at the same time.
For example without using numpy
, i would have used
mat = list(enumerate(mat)) # gives [(0, 0.05170474575702143), (1, 0.07367926270375554), (2, 0.05741241249643288), (3, 0.3487036852148175), (4, 0.19990381197331886), (5, 0.2685960818546567)]
mat.sort(reverse = True, key = lambda ×: ×[1]) # gives [(3, 0.3487036852148175), (5, 0.2685960818546567), (4, 0.19990381197331886), (1, 0.07367926270375554), (2, 0.05741241249643288), (0, 0.05170474575702143)]
However, since i am using numpy
, i was wondering if there was maybe a numpy function that can do all of that. I was able to use np.sort
and np.argsort
to sort the indexes and the values individually, but i wasn't able to do both at the same time...
indices = np.argsort(mat)[::-1]
np.hstack((indices[:, np.newaxis], mat[indices][:, np.newaxis]))
array([[3. , 0.34870369],
[5. , 0.26859608],
[4. , 0.19990381],
[1. , 0.07367926],
[2. , 0.05741241],
[0. , 0.05170475]])
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.