Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D Sorting with NumPy - sort 1 row and have the other follow the sorting

Say I have a NumPy array:

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

I want to sort the bottom row of this array, but have the top row follow the sorting, such that I get:

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

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

Any ideas? Thanks so much!

like image 838
woodstock Avatar asked Oct 26 '11 08:10

woodstock


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]
like image 157
tillsten Avatar answered Nov 03 '22 13:11

tillsten


The only (efficient) solution I can think of needs 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, that idx is the index of the sorted column.

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

That should be reasonably fast, but, of course, wastes some memory.

like image 31
alexurba Avatar answered Nov 03 '22 12:11

alexurba