简体   繁体   English

排序numpy数组时输出错误

[英]Wrong output while sorting numpy array

I have written a python code which sorts multidimensional numpy array in 2nd column in ascending order 我写了一个python代码,该代码按升序对第二列中的多维numpy数组进行排序

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 我正在使用python 2.7

I think you are missing the int call. 我认为您错过了int电话。 It is currently sorting the first values as though they were strings. 当前它正在对第一个值进行排序,就好像它们是字符串一样。 And '12' is smaller than '9' in that case. 在这种情况下,“ 12”小于“ 9”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM