RoY
RoY

Reputation: 113

Wrong output while sorting numpy array

I have written a python code which sorts multidimensional numpy array in 2nd column in ascending order

import numpy as np
xt = [['S_P' , '9'  ,'42'],['S_SB', '9', '30'],['C_G' ,'14', '17'],['T_G', '12' ,'25'],['C_O' ,'14' ,'34'],['C_P' ,'14', '39'],['C_SB' ,'14' ,'20'],['T_O','12' ,'39']]

xb =  sorted(xt , key=lambda x: x[1])
xb = np.array(xb)
print xb

The output is

[['T_G' '12' '25'] 
 ['T_O' '12' '39'] 
 ['C_G' '14' '17']  
 ['C_O' '14' '34'] 
 ['C_P' '14' '39'] 
 ['C_SB' '14' '20'] 
 ['S_P' '9' '42'] 
 ['S_SB' '9' '30']]

The outout that i was expecting is

>   [['S_P' '9' '42'] 
>      ['S_SB' '9' '30']
>      ['T_G' '12' '25'] 
>      ['T_O' '12' '39'] 
>      ['C_G' '14' '17']  
>      ['C_O' '14' '34'] 
>      ['C_P' '14' '39'] 
>      ['C_SB' '14' '20']]

I am using python 2.7

Upvotes: 1

Views: 213

Answers (1)

Garrett R
Garrett R

Reputation: 2662

I think you are missing the int call. It is currently sorting the first values as though they were strings. And '12' is smaller than '9' in that case.

xb =  sorted(xt , key=lambda x: int(x[1]))
xb = np.array(xb) 
print xb

Upvotes: 2

Related Questions