Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Arrangement of Indices for Sorting Array

I’m trying to sort in descend order an array of float (63,) called LAM.
I did using the following code and it is working.

LAM_Sorted = -np.sort(-LAM, axis=0)

What about if now I want to have also the arrangement of the elements, so an array with the same size of LAM with values indicating the previous position on the column vector of each element?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In MATLAB for example is the returned array I in the built-in sort function, explained below:

[B,I] = sort(___) also returns a collection of index vectors for any of the previous syntaxes. I is the same size as A and describes the arrangement of the elements of A into B along the sorted dimension. For example, if A is a vector, then B = A(I).

Thanks in advance, let me know.

>Solution :

Use np.argsort (docs), which returns the indices that would sort an array.

import numpy as np
a1 = np.array([1, 3, 5, 2, 4])
a2 = np.array([0.1, 0.003, 50, 0.02, 0.4])

sort_order = np.argsort(-a1) # Indices that would sort a1 in descending order
# array([2, 4, 1, 3, 0])

a1_sorted = a1[sort_order]    # Sort a1
# array([5, 4, 3, 2, 1])

a2_ordered = a2[sort_order]   # a2 is ordered by indices that would sort a1
# array([5.e+01, 4.e-01, 3.e-03, 2.e-02, 1.e-01])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading