如何将pandas数据框中的date转换为“date”数据types?

我有一个pandas数据框,其中的一列包含格式为“YYYY-MM-DD”的datestring,例如“2013-10-28”。

此刻,列的dtype是“对象”。

如何将列值转换为Pandasdate格式?

使用astype

In [31]: df Out[31]: a time 0 1 2013-01-01 1 2 2013-01-02 2 3 2013-01-03 In [32]: df['time'] = df['time'].astype('datetime64[ns]') In [33]: df Out[33]: a time 0 1 2013-01-01 00:00:00 1 2 2013-01-02 00:00:00 2 3 2013-01-03 00:00:00 

基本上相当于@waitingkuo,但我会在这里使用to_datetime (它看起来有点干净,并提供了一些额外的function,比如dayfirst ):

 In [11]: df Out[11]: a time 0 1 2013-01-01 1 2 2013-01-02 2 3 2013-01-03 In [12]: pd.to_datetime(df['time']) Out[12]: 0 2013-01-01 00:00:00 1 2013-01-02 00:00:00 2 2013-01-03 00:00:00 Name: time, dtype: datetime64[ns] In [13]: df['time'] = pd.to_datetime(df['time']) In [14]: df Out[14]: a time 0 1 2013-01-01 00:00:00 1 2 2013-01-02 00:00:00 2 3 2013-01-03 00:00:00 

我想大量的数据是从CSV文件进入pandas,在这种情况下,您可以简单地在初始CSV读取期间转换date:

dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])其中0表示date所在的列。
如果你想把date作为你的索引, index_col=0你也可以在里面添加, index_col=0

请参阅http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html

现在你可以做df['column'].dt.date

请注意,对于date时间对象,如果您没有看到他们都是00:00:00的小时,那不是pandas。 这是iPython笔记本试图让事情看起来很漂亮。

date可能需要转换为不同的频率。 在这种情况下,我build议按date设置索引。

 #set an index by dates df.set_index(['time'], drop=True, inplace=True) 

在此之后,您可以更轻松地转换为您最需要的date格式types。 在下面,我顺序转换为一些date格式,最终以月初的一组date为结束。

 #Convert to daily dates df.index = pd.DatetimeIndex(data=df.index) #Convert to monthly dates df.index = df.index.to_period(freq='M') #Convert to strings df.index = df.index.strftime('%Y-%m') #Convert to daily dates df.index = pd.DatetimeIndex(data=df.index) 

为了简洁起见,我没有表明在每行之后运行以下代码:

 print(df.index) print(df.index.dtype) print(type(df.index)) 

这给了我以下输出:

 Index(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='object', name='time') object <class 'pandas.core.indexes.base.Index'> DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03'], dtype='datetime64[ns]', name='time', freq=None) datetime64[ns] <class 'pandas.core.indexes.datetimes.DatetimeIndex'> PeriodIndex(['2013-01', '2013-01', '2013-01'], dtype='period[M]', name='time', freq='M') period[M] <class 'pandas.core.indexes.period.PeriodIndex'> Index(['2013-01', '2013-01', '2013-01'], dtype='object') object <class 'pandas.core.indexes.base.Index'> DatetimeIndex(['2013-01-01', '2013-01-01', '2013-01-01'], dtype='datetime64[ns]', freq=None) datetime64[ns] <class 'pandas.core.indexes.datetimes.DatetimeIndex'>