1

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!

1 Answer 1

0

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.