How to sort a numpy array in a specific order given by a separate list depending on the relative sizes of the values ​​in the array

In a piece of code, I already have a numpy array created and I want to sort this 1st array given a specific order given in the list. The result will be the third array (new_values).

In the first array, the values ​​will be sorted.

values = numpy.array([10.0, 30.1, 50, 40, 20])

      

The list represents the order specified by the indices of the values ​​in new_values, which must be in descending order, where 0 is the largest number.

order=[0, 3, 1, 4, 2].

      

So,

new_values[0] > new_values[3] > new_values[1] > new_values[4] > new_values[2]

      

I tried to find a specific sorting function to accomplish this like argsort or with a key, however I didn't figure out how to adapt them to this situation.

Is there a simple quick way to accomplish this as I will be doing this for many iterations. I am willing to change the second array, ordering, to specify the indices in a different way if it was beneficial to sort with a better method.

I am currently using the following for loop.

size=len(values)
new_values = np.zeros(size)
values = sorted(values,reverse=True)

    for val in range(0, size):
        new_values[int(order[val])] = values[val] 

      

Thank you in advance!

+3


source to share


1 answer


You can simply use indexing for this:

>>> import numpy as np
>>> values = np.array([10.0, 30.1, 50, 40, 20])
>>> order=[0, 3, 1, 4, 2]
>>> sorted_array=values[order]
>>> sorted_array
array([ 10. ,  40. ,  30.1,  20. ,  50. ])

      

Also like @Divakar mentioned in the comment if you want the following condition:



new_values[0] > new_values[3] > new_values[1] > new_values[4] > new_values[2]

      

You can do:

>>> values[order]=np.sort(values)[::-1]
>>> values
array([ 50. ,  30.1,  10. ,  40. ,  20. ])

      

+3


source







All Articles