pythonpandaslistsorting

Sort list of dates by year & quarter


Let's say I have a list:

Date = ['2015-Q1', '2013-Q4', '2017-Q2', '2018-Q1']

How can I sort it into chronological order such that:

Date = ['2013-Q4', '2015-Q1', '2017-Q2', '2018-Q1']

Solution

  • By using natsort
    natsort provides a function natsorted that helps sort lists “naturally” (“naturally” is rather ill-defined, but in general it means sorting based on meaning and not computer code point)

    import natsort
    natsort.natsorted(Date)
    Out[103]: ['2013-Q4', '2015-Q1', '2017-Q2', '2018-Q1']