1

I have a list with the length of n:

labels = ['a', 'b', 'c', 'd']

and a array with the size of m*n like:

values = array([[0. , 0.6, 0.3, 0.1],
                [0.5, 0.1, 0.1, 0.3],
                [0.1, 0.2, 0.3, 0.4]])

I wish to sort labels by each line of values and to generate a new m*n array like:

labels_new = [['a', 'd', 'c', 'b'],
                ['b', 'c', 'd', 'a'],
                ['a', 'b', 'c', 'd']]

Is there any simple way to achieve this?

2 Answers 2

3

You can use argsort function. Just use a numpy array for preserving the labels and then a simple indexing:

In [6]: labels = np.array(['a', 'b', 'c', 'd'])                                                                                                                                                             

In [7]: labels[np.argsort(values)]                                                                                                                                                                          
Out[7]: 
array([['a', 'd', 'c', 'b'],
       ['b', 'c', 'd', 'a'],
       ['a', 'b', 'c', 'd']], dtype='<U1')
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible to reverse the list? I need to sort labels by values from the maximum to the minimum.
@zhangboyu just reverse the order of argsort's result columns'; np.argsort(values)[:,::-1]
0

Function argsort arranges an array in a srted order and returns the corresponding array of indexes. That array can be used to reorder the labels:

[array(labels)[np.argsort(v)].tolist() for v in values]
#[['a', 'd', 'c', 'b'], 
# ['b', 'c', 'd', 'a'], 
# ['a', 'b', 'c', 'd']]

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.