2

I want to sort the rows of a 2D array based on the elements of the first column, in Python 3. For example, if

    x = array([[ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ],
               [ 2. ,  6. ,  7. ,  9. ]])

then I need the sorted array to be

    x = array([[ 2. ,  6. ,  7. ,  9. ],
               [ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ]])

How can I do that? A similar question was asked and answered here, but it does not work for me.

CLAUDE
  • 294
  • 1
  • 2
  • 11
  • If my answer suits you, please consider [accepting](https://stackoverflow.com/help/accepted-answer) it – Charles Aug 09 '19 at 17:42

2 Answers2

1

The following should work:

import numpy as np
x = np.array([[ 5. ,  9. ,  2. ,  6. ],
               [ 7. , 12. ,  3.5,  8. ],
               [ 2. ,  6. ,  7. ,  9. ]])

x[x[:, 0].argsort()]
Out[2]:
array([[ 2. ,  6. ,  7. ,  9. ],
       [ 5. ,  9. ,  2. ,  6. ],
       [ 7. , 12. ,  3.5,  8. ]])

Documentation : numpy.argsort

Charles
  • 324
  • 1
  • 13
1
#using sorted    
x = ([[5.,9.,2.,6. ], [7.,12.,3.5,8.], [2.,6.,7.,9.]])
x = sorted(x, key=lambda i: i[0]) #1st col 
print(x)
geekzeus
  • 785
  • 5
  • 14