0

I have this np array:

array([[0, 0, 0, 0, 4, 4],
       [2, 3, 5, 6, 5, 6]])

I want to sort it by the second row so the first row will adjust accordingly. So the output should be like this:

array([[0, 0, 0, 4, 0, 4],
       [2, 3, 5, 5, 6, 6]])

Is there a quick way to do it?

Phoenix
  • 73
  • 1
  • 7
  • Each object on the first row should be connected to the element on the same location on the second row. So if some element on the second row changes its location, it's 'partner' element on the first row will move to the new location on the first row. – Phoenix Aug 01 '18 at 09:50
  • @LucaCappelletti: The other question wants to sort an array's rows based on a particular column, while this wants to sort the columns based on a particular row. That makes the questions similar, but different enough that many people could not make the connection. – Rory Daulton Aug 01 '18 at 09:52

1 Answers1

5

You can use np.argsort() to get the indices of sorted version of the second row and use those indices to rearrange your array's columns:

In [38]: a = np.array([[0, 0, 0, 0, 4, 4],
    ...:        [2, 3, 5, 6, 5, 6]])
    ...:        

In [39]: a[:, np.argsort(a[1])]
Out[39]: 
array([[0, 0, 0, 4, 0, 4],
       [2, 3, 5, 5, 6, 6]])
Mazdak
  • 105,000
  • 18
  • 159
  • 188