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 Answers1

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]
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Is there a way to do argsort() in descending order. –  Nov 11 '19 at 14:04
  • @Zanthoxylumpiperitum - Yop [this](https://stackoverflow.com/questions/16486252/is-it-possible-to-use-argsort-in-descending-order). – jezrael Nov 11 '19 at 14:05
  • 1
    @Zanthoxylumpiperitum - `df = df.iloc[pd.to_datetime(df['Date'], format='%b%y').argsort()[::-1]]` – jezrael Nov 11 '19 at 14:06