I have an arbitrary list of date strings (mm-yyyy) as follows:
d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'...]
I need this list to be sorted first by the level of years (ascending), then on the level of months (ascending)..so that the logical ordering can be:
d_ordered = ['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013' ...]
How can I achieve this?
To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.
You can simply use an array of day string in the function, and then use the day week number to sort elements like a boss.
One thing to notice here is our DataFrame gets sorted in ascending order of dates, to sort the DataFrame in descending order we can pass an additional parameter inside the sort_values() function that will set ascending value to False and will return the DataFrame in descending order.
Try this:
import datetime d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'] sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
Use sorted()
with a key:
>>> d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'] >>> def sorting(L): ... splitup = L.split('-') ... return splitup[1], splitup[0] ... >>> sorted(d, key=sorting) ['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013']
It's better to use a function here instead of a lambda to prevent calling split()
twice (and it looks a bit neater :))
Note that this will return the sorted list. If you want to sort it in place, use .sort()
:
>>> d.sort(key=sorting) >>> d ['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With