繁体   English   中英

Python:如何使用字符串和整数的组合对数组进行排序

[英]Python: How to sort an Array with with a combination of Strings and Integers

我有以下数组来表示数据框中列的范围:

array(['72.5 - 80.0', '42.5 - 50.0', '57.5 - 65.0', '20.0 - 27.5',
   '35.0 - 42.5', '147.5 - 155.0', '192.5 - 200.0', '87.5 - 95.0',
   '95.0 - 102.5', '185.0 - 192.5', '117.5 - 125.0', '102.5 - 110.0',
   '162.5 - 170.0', '80.0 - 87.5', '170.0 - 177.5', '65.0 - 72.5',
   '140.0 - 147.5', '110.0 - 117.5', '132.5 - 140.0', '27.5 - 35.0',
   '50.0 - 57.5', '177.5 - 185.0', '155.0 - 162.5'], dtype=object)

我想对其进行排序,使其看起来像这样,基本上按升序排列:

 array(['20.0 - 27.5', '27.5 - 35.0', '35.0 - 42.5', '42.5 - 50.0', ......

我该怎么办? 谢谢!

您可以使用natsort

from natsort import natsorted

np.array(natsorted(a), dtype=object)

或使用自定义key sorted

np.array(sorted(a, key=lambda x: float(x.split('-')[0])), dtype=object)

输出:

array(['20.0 - 27.5', '27.5 - 35.0', '35.0 - 42.5', '42.5 - 50.0',
       '50.0 - 57.5', '57.5 - 65.0', '65.0 - 72.5', '72.5 - 80.0',
       '80.0 - 87.5', '87.5 - 95.0', '95.0 - 102.5', '102.5 - 110.0',
       '110.0 - 117.5', '117.5 - 125.0', '132.5 - 140.0', '140.0 - 147.5',
       '147.5 - 155.0', '155.0 - 162.5', '162.5 - 170.0', '170.0 - 177.5',
       '177.5 - 185.0', '185.0 - 192.5', '192.5 - 200.0'], dtype=object)

暂无
暂无

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

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