Search code examples
pandasdataframegroup-by

How to sort object data type index into datetime in pandas?


Index(['Apr-20', 'Apr-21', 'Apr-22', 'Aug-20', 'Aug-21', 'Aug-22', 'Dec-20', 'Dec-21', 'Dec-22', 'Feb-21', 'Feb-22', 'Jan-21', 'Jan-22', 'Jan-23', 'Jul-20', 'Jul-21', 'Jul-22', 'Jun-20', 'Jun-21', 'Jun-22', 'Mar-20', 'Mar-21', 'Mar-22', 'May-20', 'May-21', 'May-22', 'Nov-20', 'Nov-21', 'Nov-22', 'Oct-20', 'Oct-21', 'Oct-22', 'Sep-20', 'Sep-21', 'Sep-22'], dtype='object', name='months')

How could I sort this month-year object dtype into the datetime format such as 'MMM-YY' in pandas? Take thanks in advance!


Solution

  • If need only sorting values of index like datetimes use DataFrame.sort_index with key parameter:

    df = df.sort_index(key=lambda x: pd.to_datetime(x, format='%b-%y'))
    

    If need DatetimeIndex and then sorting use:

    df.index = pd.to_datetime(df.index, format='%b-%y')
    df = df.sort_index()
    

    Another idea is create PeriodIndex:

    df.index = pd.to_datetime(df.index, format='%b-%y').to_period('m')
    df = df.sort_index()