JoVe JoVe - 1 year ago 295
Python Question

sort an array by row in python

I understood that sorting a numpy array

by column (for only a particular column, for example, its 2nd column) can be done with:


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

Now I wonder what if I want to sort the array
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 is the size of the 2d array) I tried to do something like
to indicate the numbers of the columns but it does not work.

EXAMPLE of what I want:

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

=> array I got with

=> array I tried to got in a simple way with
but did not succeed

Answer Source

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


to sort by column and


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



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


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download