Sort date in string format in a pandas dataframe?

懵懂的女人 提交于 2021-02-16 20:06:58

问题


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:


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]


来源:https://stackoverflow.com/questions/58750432/sort-date-in-string-format-in-a-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!