Home > Enterprise >  Arrangement of Indices for Sorting Array
Arrangement of Indices for Sorting Array

Time:12-15

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?

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.

CodePudding user response:

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