Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a numpy array based on the values in a specific row?

I was wondering how I would be able to sort a whole array by the values in one of its columns.

I have :

array([5,2,8,2,4])

and:

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24]])

I want to append the first array to the second one like this:

array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24],
       [5,  2,  8,  2,  4]])

And then sort the array by the appended row to get either this:

array([[1,  3,  4,  0,  2],
       [6,  8,  9,  5,  7],
       [11, 13, 14, 10, 12],
       [16, 18, 19, 15, 17],
       [21, 23, 24, 20, 22],
       [2,  2,  4,  5,  8]])

or this:

array([[ 2,  1,  3,  4,  0],
       [ 7,  6,  8,  9,  5],
       [12, 11, 13, 14, 10],
       [17, 16, 18, 19, 15],
       [22, 21, 23, 24, 20],
       [ 8,  5,  4,  2,  2]])

And then remove the appended column to get:

array([[1,  3,  4,  0,  2],
       [6,  8,  9,  5,  7],
       [11, 13, 14, 10, 12],
       [16, 18, 19, 15, 17],
       [21, 23, 24, 20, 22]])

or:

array([[ 2,  1,  3,  4,  0],
       [ 7,  6,  8,  9,  5],
       [12, 11, 13, 14, 10],
       [17, 16, 18, 19, 15],
       [22, 21, 23, 24, 20]])

Is there a code to carry out this procedure. I am very new to python. Thanks a lot!

like image 540
tooty44 Avatar asked Jun 20 '14 16:06

tooty44


People also ask

How do you sort an array based on the second column in Python?

Use the syntax array[:, j - 1] to extract the j -th column of an array. Call numpy. argsort(a) to return the sorted indices of the column a . Then use these sorted indices to sort the rows of the same array by column a .

How do I sort a NumPy array in descending order?

In Numpy, the np. sort() function does not allow us to sort an array in descending order. Instead, we can reverse an array utilizing list slicing in Python, after it has been sorted in ascending order.


1 Answers

You can use numpy.argsort to get a list with the sorted indices of your array. Using that you can then rearrange the columns of the matrix.

import numpy as np

c = np.array([5,2,8,2,4])    
a = np.array([[ 0,  1,  2,  3,  4],
              [ 5,  6,  7,  8,  9],
              [10, 11, 12, 13, 14],
              [15, 16, 17, 18, 19],
              [20, 21, 22, 23, 24]])

i = np.argsort(c)
a = a[:,i]
like image 165
pezcode Avatar answered Oct 09 '22 03:10

pezcode