【发布时间】:2015-05-31 15:45:51
【问题描述】:
我有一个包含一些日期时间(作为字符串)和一些空值作为“nan”的系列:
import pandas as pd, numpy as np, datetime as dt
df = pd.DataFrame({'Date':['2014-10-20 10:44:31', '2014-10-23 09:33:46', 'nan', '2014-10-01 09:38:45']})
我正在尝试将这些转换为日期时间:
df['Date'] = df['Date'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))
但我得到了错误:
time data 'nan' does not match format '%Y-%m-%d %H:%M:%S'
所以我试着把这些变成实际的空值:
df.ix[df['Date'] == 'nan', 'Date'] = np.NaN
然后重复:
df['Date'] = df['Date'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))
然后我得到错误:
必须是字符串,不能是浮点数
解决这个问题的最快方法是什么?
【问题讨论】:
标签: python string datetime pandas type-conversion