2D Sort with NumPy - sort 1 row, and another - sort

Let's say I have a NumPy array:

[[4 9 2] [5 1 3]] 

I want to sort the bottom row of this array, but the top row follows the sort to get:

 [[9 2 4] [1 3 5]] 

I know that you can sort like this using the sorted () function, but this requires input and output of lists.

Any ideas? Many thanks!

+7
source share
2 answers
 import numpy as np a = np.array([[4,9,2],[5,1,3]]) idx = np.argsort(a[1]) 

Now you can use idx to index your array:

 b=a[:,idx] 
+12
source

The only (effective) solution I can think of is to need a copy of the original array.

 import numpy as np a = np.array([[4,9,2],[5,1,3]]) idx = np.argsort(a[1]) 

So idx is the index of the sorted column.

 c = a.copy() for i in range(len(idx)): a[:,i] = c[:,idx[i]] 

It should be fast enough, but, of course, takes some memory.

+1
source

All Articles