Python数据框架转换多个日期时间格式

20

我有一个像这样的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 

我想将它们转换为日期时间格式,考虑使用:

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'))

显然,它们两个都适用于整个数据框。我在考虑使用try和except但没有成功,有什么建议吗?


1
for item in test_df.col: test_df.col = datetime.strptime(test_df.col, '%m/%d/%Y') - Christopher Pearson
你是在指 pandas 数据框吗? - TigerhawkT3
@Christopher Pearson 哦,你的意思是对于每个项目都要尝试和捕获异常,对吗?谢谢! - datadatadata
@TigerhawkT3 是的!pandas。抱歉没有提到它...我已经更新了我的问题,谢谢。 - datadatadata
4个回答

19

只需使用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

现在,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

1
我猜这个解决方案的问题在于你提供了一个加快速度的格式 - 没有格式的to_datetime非常慢。 - morganics
@Ian 是的,但如果你没有固定的格式,那么你必须这样做。 - EdChum
@EdChum - 我认为如果你有相当数量的数据,使用to_datetime会太慢。我在下面添加了我的答案。 - morganics

17

我在同一列Temps中有两种不同的日期格式,与原帖类似,看起来像以下内容:

01.03.2017 00:00:00.000
01/03/2017 00:13

这两个代码片段的时间如下;

v['Timestamp1'] = pd.to_datetime(v.Temps)

用了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')

花费0.2923243045806885秒

换句话说,如果您的日期时间只有少数已知格式,请勿在没有指定格式的情况下使用to_datetime!


1
这是一个好的解决方案,如果您知道真实世界数据的困难,甚至可以添加一个检查语句,在已知日期格式的迭代之后,如果仍有空值,则将通用的to_datetime应用于剩余的值。除了上述速度提升外,这还有助于最小化混淆天数/月份和产生错误结果的风险。 - Iain D

1
您可以创建一个新的列:

test_df['col1'] = pd.Timestamp(test_df['col']).to_datetime()

然后删除列并将col1重命名。

1

这对我很有效。

  • 我的“fecha_hechos”列中有两个格式。这些格式是:
  • 2015/03/02
  • 10/02/2010

我所做的是:

carpetas_cdmx['Timestamp'] = pd.to_datetime(carpetas_cdmx.fecha_hechos, format='%Y/%m/%d %H:%M:%S', errors='coerce')
mask = carpetas_cdmx.Timestamp.isnull()
carpetas_cdmx.loc[mask, 'Timestamp'] = pd.to_datetime(carpetas_cdmx[mask]['fecha_hechos'], format='%d/%m/%Y %H:%M',errors='coerce')

这里: carpetas_cdmx 是我的数据框,fecha_hechos 是我的格式列。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接