如何使用null将字符串转换为datetime - python,pandas?

Col*_*ien 11 python string datetime type-conversion pandas

我有一个系列有一些日期时间(作为字符串)和一些空值为'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']})
Run Code Online (Sandbox Code Playgroud)

我正在尝试将这些转换为日期时间:

df['Date'] = df['Date'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

time data 'nan' does not match format '%Y-%m-%d %H:%M:%S'
Run Code Online (Sandbox Code Playgroud)

所以我试着把它们变成实际的空值:

df.ix[df['Date'] == 'nan', 'Date'] = np.NaN
Run Code Online (Sandbox Code Playgroud)

并重复:

df['Date'] = df['Date'].apply(lambda x: dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))
Run Code Online (Sandbox Code Playgroud)

但后来我得到了错误:

必须是字符串,而不是浮动

解决这个问题的最快方法是什么?

EdC*_*ica 25

只需使用to_datetime并设置errors='coerce'处理duff数据:

In [321]:

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df
Out[321]:
                 Date
0 2014-10-20 10:44:31
1 2014-10-23 09:33:46
2                 NaT
3 2014-10-01 09:38:45

In [322]:

df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 4 entries, 0 to 3
Data columns (total 1 columns):
Date    3 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 64.0 bytes
Run Code Online (Sandbox Code Playgroud)

调用的问题strptime是,如果字符串或dtype不正确,它将引发错误.

如果你这样做,那么它会工作:

In [324]:

def func(x):
    try:
        return dt.datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
    except:
        return pd.NaT

df['Date'].apply(func)
Out[324]:
0   2014-10-20 10:44:31
1   2014-10-23 09:33:46
2                   NaT
3   2014-10-01 09:38:45
Name: Date, dtype: datetime64[ns]
Run Code Online (Sandbox Code Playgroud)

但是使用内置to_datetime而不是调用将更快,apply这实际上只是循环你的系列.

计时

In [326]:

%timeit pd.to_datetime(df['Date'], errors='coerce')
%timeit df['Date'].apply(func)
10000 loops, best of 3: 65.8 µs per loop
10000 loops, best of 3: 186 µs per loop
Run Code Online (Sandbox Code Playgroud)

我们在这里看到使用to_datetime速度提高了3倍.

  • 现在的语法是`errors ='coerce'`而不是`coerce = True`. (8认同)