我有一个Pandas数据框,其中一列包含格式为'YYYY-MM-DD'的日期字符串,例如'2013年10月28日'。
目前,该列的dtype是'object'。
如何将列值转换为Pandas日期格式?
答案 0 :(得分:90)
基本上等同于@waitingkuo,但我会在这里使用to_datetime
(它看起来更清晰,并提供一些额外的功能,例如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
处理ValueError
s
如果你遇到了做
df['time'] = pd.to_datetime(df['time'])
抛出一个
ValueError: Unknown string format
这意味着您有无效(不可强制)的值。如果您将它们转换为pd.NaT
即可,则可以向errors='coerce'
添加to_datetime
参数:
df['time'] = pd.to_datetime(df['time'], errors='coerce')
答案 1 :(得分:77)
使用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
答案 2 :(得分:24)
我想很多数据都会从CSV文件中传入Pandas,在这种情况下,您可以在初始CSV读取过程中简单地转换日期:
dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])
其中0表示日期所在的列。
如果您希望将日期作为索引,也可以在其中添加, index_col=0
。
请参阅http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html
答案 3 :(得分:17)
现在你可以df['column'].dt.date
请注意,对于日期时间对象,如果您没有看到他们全部00:00:00的小时,那么这不是大熊猫。这款iPython笔记本试图让它看起来很漂亮。
答案 4 :(得分:0)
可能需要将日期转换为不同的频率。在这种情况下,我建议按日期设置索引。
#set an index by dates
df.set_index(['time'], drop=True, inplace=True)
在此之后,您可以更轻松地转换为您最需要的日期格式类型。下面,我按顺序转换为多种日期格式,最终以月初的一组日期结束。
#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'>
答案 5 :(得分:0)
执行此操作的另一种方法,如果您有多个要转换为日期时间的列,则此方法效果很好。
cols = ['date1','date2']
df[cols] = df[cols].apply(pd.to_datetime)
答案 6 :(得分:0)
如果要获取DATE而不是DATETIME格式:
df["id_date"] = pd.to_datetime(df["id_date"]).dt.date
答案 7 :(得分:0)
尝试使用pd.to_datetime函数将行之一转换为时间戳,然后使用.map将公式化器映射到整个列
答案 8 :(得分:0)
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 startDay 110526 non-null object
1 endDay 110526 non-null object
import pandas as pd
df['startDay'] = pd.to_datetime(df.startDay)
df['endDay'] = pd.to_datetime(df.endDay)
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 startDay 110526 non-null datetime64[ns]
1 endDay 110526 non-null datetime64[ns]
答案 9 :(得分:0)
出于完整性考虑,另一种选择(可能不是最简单的选择)与@SSS提出的选择有点类似,但使用的是datetime库:
import datetime
df["Date"] = df["Date"].apply(lambda x: datetime.datetime.strptime(x, '%Y-%d-%m').date())