Skip to content
Advertisement

How can I sort 2d array includes only string characters in Python?

There is an array as below;

x=np.array([ ['0', '0'],
             ['1', '1'],
             ['7', '10'],
             ['8', '11'],
             [',', '2'],
             ['4', '3'],
             ['.', '4'],
             ['2', '5'],
             ['5', '6'],
             ['er014', '7'],
             ['ww', '8'],
             ['*', '9']])

I used the following codes to sort this array by the second column but without success. Is there anyone to help?

A= np.take(x, x[:, 1].argsort(), 0) 

Advertisement

Answer

np.take(x, x[:, 1].astype(int).argsort(), 0)
You may just cast the values for sorting. The overall result of you np.take() will remain as strings.

array([['0', '0'],
   ['1', '1'],
   [',', '2'],
   ['4', '3'],
   ['.', '4'],
   ['2', '5'],
   ['5', '6'],
   ['er014', '7'],
   ['ww', '8'],
   ['*', '9'],
   ['7', '10'],
   ['8', '11']], dtype='<U5')
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement