JoVe - 4 months ago 16

Python Question

I understood that sorting a numpy array

`arr`

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

How I understood this code sample works:

`argsort`

`arr`

`arr`

Now I wonder what if I want to sort the array

`arr`

Instead of doing

`(n,n)array[(n,)array]`

`(n,n)array[(n,1)array]`

EXAMPLE of what I want:

`arr = [[11,25],[33,4]]`

`arr_col2=[[33,4],[11,25]]`

`argsort()`

`arr_row2=[[25,11],[4,33]]`

`argsort()`

Answer

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 n^{th} row goes in increasing order. You can do this simply by

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

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