dat*_*ata 9 python datetime dataframe pandas
我有一个像这样的pandas.dataframe('col'列有两种格式):
col val
'12/1/2013' value1
'1/22/2014 12:00:01 AM' value2
'12/10/2013' value3
'12/31/2013' value4
Run Code Online (Sandbox Code Playgroud)
我想将它们转换为datetime,我正在考虑使用:
test_df['col']= test_df['col'].map(lambda x: datetime.strptime(x, '%m/%d/%Y'))
test_df['col']= test_df['col'].map(lambda x: datetime.strptime(x, '%m/%d/%Y %H:%M %p'))
Run Code Online (Sandbox Code Playgroud)
显然,它们中的任何一个都适用于整个df.我正在考虑使用尝试,除了但没有任何运气,任何建议?
只需使用to_datetime,它的男人/女人就足以处理这两种格式:
In [4]:
df['col'] = pd.to_datetime(df['col'])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 4 entries, 0 to 3
Data columns (total 2 columns):
col 4 non-null datetime64[ns]
val 4 non-null object
dtypes: datetime64[ns](1), object(1)
memory usage: 96.0+ bytes
Run Code Online (Sandbox Code Playgroud)
df现在看起来像这样:
In [5]:
df
Out[5]:
col val
0 2013-12-01 00:00:00 value1
1 2014-01-22 00:00:01 value2
2 2013-12-10 00:00:00 value3
3 2013-12-31 00:00:00 value4
Run Code Online (Sandbox Code Playgroud)
我在同一列中有两种不同的日期格式Temps,类似于OP,如下所示;
01.03.2017 00:00:00.000
01/03/2017 00:13
Run Code Online (Sandbox Code Playgroud)
两种不同代码段的时序如下:
v['Timestamp1'] = pd.to_datetime(v.Temps)
Run Code Online (Sandbox Code Playgroud)
花费了25.5408718585968秒
v['Timestamp'] = pd.to_datetime(v.Temps, format='%d/%m/%Y %H:%M', errors='coerce')
mask = v.Timestamp.isnull()
v.loc[mask, 'Timestamp'] = pd.to_datetime(v[mask]['Temps'], format='%d.%m.%Y %H:%M:%S.%f',
errors='coerce')
Run Code Online (Sandbox Code Playgroud)
花费0.2923243045806885秒
换句话说,如果日期时间的已知格式数量很少,请不要在没有格式的情况下使用to_datetime!