我的Python程序以pandas格式生成数据文件
Source LogP MolWt HBA HBD
0 cne_1 1.1732 263.405 3 1
1 cne_10 2.6639 197.237 2 0
2 cne_100 -0.2886 170.193 4 2
3 cne_1000 1.9644 304.709 5 1
4 cne_1001 1.4986 162.144 3 1
... ... ... ... ... ...
1031 cne_995 3.0179 347.219 4 2
1032 cne_996 4.8419 407.495 6 2
1033 cne_997 3.3560 354.524 3 1
1034 cne_998 7.5465 635.316 4 2
1035 cne_999 3.3514 389.556 4 1
我需要根据数字根据第二(源)列对字符串进行排序,因此排序后的行的正确顺序应为:cne_1,cne_2,cne_3,cne_4等,我尝试使用:
df_sorted = df.sort_values('Source', ascending=True)
但它不会延迟行顺序的任何变化。
对于最后的熊猫版本,可以使用key
带分割值的参数by_
并将值转换为整数:
df_sorted = df.sort_values('Source', key=lambda x: x.str.split('_').str[1].astype(int))
或者可能Series.argsort
通过来获得排序值的位置并传递给DataFrame.iloc
:
df_sorted = df.iloc[df['Source'].str.split('_').str[1].astype(int).argsort()]
print (df_sorted)
Source LogP MolWt HBA HBD
0 cne_1 1.1732 263.405 3 1
1 cne_10 2.6639 197.237 2 0
2 cne_100 -0.2886 170.193 4 2
1031 cne_995 3.0179 347.219 4 2
1032 cne_996 4.8419 407.495 6 2
1033 cne_997 3.3560 354.524 3 1
1034 cne_998 7.5465 635.316 4 2
1035 cne_999 3.3514 389.556 4 1
3 cne_1000 1.9644 304.709 5 1
4 cne_1001 1.4986 162.144 3 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句