在 pandas 数据框中以字符串格式对日期进行排序? [英] Sort date in string format in a pandas dataframe?
本文介绍了在 pandas 数据框中以字符串格式对日期进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的数据框,如何排序.
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 ?
推荐答案
首先将列转换为日期时间,并通过 DataFrame.iloc
:
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
详细信息:
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]
这篇关于在 pandas 数据框中以字符串格式对日期进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文