简体   繁体   English

Python:NumPy排序数组

[英]Python : NumPy sorting array

I am currently trying to sort a numpy array, but i am running into a difficulty我目前正在尝试对 numpy 数组进行排序,但我遇到了困难

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例如,不使用numpy ,我会使用

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.但是,由于我使用的是numpy ,我想知道是否可能有一个 numpy function 可以做到所有这些。 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...我能够使用np.sortnp.argsort分别对索引和值进行排序,但我无法同时进行这两项操作......

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]])

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

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