2

I have a dataframe like this, how to sort this.

  df = pd.DataFrame({'Date':['Oct20','Nov19','Jan19','Sep20','Dec20']})


        Date
    0   Oct20
    1   Nov19
    2   Jan19
    3   Sep20
    4   Dec20

I familiar in sorting list of dates(string)

 a.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))

Any thoughts? Should i split it ?

1 Answer 1

5

First convert column to datetimes and get positions of sorted values by Series.argsort what is used for change ordering with DataFrame.iloc:

df = df.iloc[pd.to_datetime(df['Date'], format='%b%y').argsort()]
print (df)
    Date
2  Jan19
1  Nov19
3  Sep20
0  Oct20
4  Dec20

Details:

print (pd.to_datetime(df['Date'], format='%b%y'))
0   2020-10-01
1   2019-11-01
2   2019-01-01
3   2020-09-01
4   2020-12-01
Name: Date, dtype: datetime64[ns]
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to do argsort() in descending order.
@Zanthoxylumpiperitum - Yop this.
@Zanthoxylumpiperitum - df = df.iloc[pd.to_datetime(df['Date'], format='%b%y').argsort()[::-1]]

Your Answer

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