4

Within a piece of code I have a numpy array already constructed, and I want to sort this 1st array given a specific order specified in a list. The result will be a 3rd array (new_values).

The 1st array has the values to be sorted.

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

The list provides the order given by the indices of the values in new_values which should be in descending order where 0 corresponds to 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 sort function to accomplish this such as argsort or with a key, however I did not understand how to adapt these to this situation.

Is there a simple quick method to accomplish this as I will be doing this for many iterations. I am willing to change the 2nd array, order, to specify the indices in another way if this was advantageous to sorting with a better method.

Currently I am 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!

1 Answer 1

4

You can simply use indexing for that :

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

7 Comments

Think, it should be the other way: sorted_array[order]=sorted(values,reverse=True) ?
@Divakar what you mean?
I mean if you are trying to get new_values as the final output, that comes out to be array([ 50. , 30.1, 10. , 40. , 20. ]), which I am assuming to be equivalent to your sorted_array, you might have to index it like sorted_array[order] = values, where values = sorted(values,reverse=True).
@Kasra No worries! Don't forget to initialize that array before indexing.
Thank you to @Kasra for the posted answer. The code above in the final part of Kasra 's answer worked fine and I have implemented it in my exisiting code. It is a simpler and quicker method than that which I was using and I can use this lesson in future code. Perfect! Also thanks for working out the answer so quickly.
|

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.