[英]How to sort a 2 dimention array of integers? In python 3 with numpy
[英]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.