I have the following array to represent the ranges for a column within a dataframe:
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)
I would like to sort it such that it looks something like this, basically in ascending order:
array(['20.0 - 27.5', '27.5 - 35.0', '35.0 - 42.5', '42.5 - 50.0', ......
How should I go about it? Thank you!
You can use natsort
:
from natsort import natsorted
np.array(natsorted(a), dtype=object)
Or sorted
with a custom key
:
np.array(sorted(a, key=lambda x: float(x.split('-')[0])), dtype=object)
Output:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.