JoVe
JoVe

Reputation: 495

sort an array by row in python

I understood that sorting a numpy array arr by column (for only a particular column, for example, its 2nd column) can be done with:

arr[arr[:,1].argsort()]

How I understood this code sample works: argsort sorts the values of the 2nd column of arr, and gives the corresponding indices as an array. This array is given to arr as row numbers. Am I correct in my interpretation?

Now I wonder what if I want to sort the array arr with respect to the 2nd row instead of the 2nd column? Is the simplest way to transpose the array before sorting it and transpose it back after sorting, or is there a way to do it like previously (by giving an array with the number of the columns we wish to display)?

Instead of doing (n,n)array[(n,)array] (n is the size of the 2d array) I tried to do something like (n,n)array[(n,1)array] to indicate the numbers of the columns but it does not work.

EXAMPLE of what I want:

arr = [[11,25],[33,4]] => base array

arr_col2=[[33,4],[11,25]] => array I got with argsort()

arr_row2=[[25,11],[4,33]] => array I tried to got in a simple way with argsort() but did not succeed

Upvotes: 2

Views: 13900

Answers (1)

Josh Hunt
Josh Hunt

Reputation: 610

I assume that arr is a numpy array? I haven't seen the syntax arr[:,1] in any other context in python. It would be worth mentioning this in your question!

Assuming this is the case, then you should be using

arr.sort(axis=0)

to sort by column and

arr.sort(axis=1)

to sort by row. (Both sort in-place, i.e. change the value of arr. If you don't want this you can copy arr into another variable first, and apply sort to that.)

If you want to sort just a single row (in this case, the second one) then

arr[1,:].sort()

works.

Edit: I now understand what problem you are trying to solve. You would like to reorder the columns in the matrix so that the nth row goes in increasing order. You can do this simply by

arr[:,arr[1,:].argsort()]

(where here we're sorting by the 2nd row).

Upvotes: 3

Related Questions