问题描述
我有一个熊猫数据框,如下所示:
I have a pandas dataframe as follows:
Symbol Date
A 02/20/2015
A 01/15/2016
A 08/21/2015
我想按Date
对其进行排序,但该列只是一个object
.
I want to sort it by Date
, but the column is just an object
.
我试图将列设置为日期对象,但是遇到了一个问题,即该格式不是所需的格式.所需的格式为2015-02-20,
等.
I tried to make the column a date object, but I ran into an issue where that format is not the format needed. The format needed is 2015-02-20,
etc.
所以现在我想弄清楚如何让numpy将美国"日期转换为ISO标准,以便可以使它们成为日期对象,从而可以对它们进行排序.
So now I'm trying to figure out how to have numpy convert the 'American' dates into the ISO standard, so that I can make them date objects, so that I can sort by them.
我该如何将这些美国日期转换为ISO标准,或者熊猫中还缺少我更直接的方法?
How would I convert these american dates into ISO standard, or is there a more straight forward method I'm missing within pandas?
推荐答案
您可以使用pd.to_datetime()
转换为日期时间对象.它带有一个format参数,但是在您的情况下,我认为您不需要它.
You can use pd.to_datetime()
to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.
>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
Date Symbol
0 02/20/2015 A
1 01/15/2016 A
2 08/21/2015 A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
对于以后的搜索,您可以更改sort语句:
For future search, you can change the sort statement:
>>> df.sort_values(by='Date') # This now sorts in date order
Date Symbol
0 2015-02-20 A
2 2015-08-21 A
1 2016-01-15 A
这篇关于按日期对 pandas 数据框进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!