0

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...

2
  • 1
    You can zip the result of np.sort and np.argsort together Commented Mar 13, 2021 at 17:10
  • @Pygirl great! Is there a way to sort by descending order, kind of like a reverse=True. Right now i am using np.flip, but i was wondering if there was a way to tell numpy to sort by descending order? Commented Mar 13, 2021 at 17:13

1 Answer 1

1
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]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.