为什么pd.to_datetime无法转换?

时间:2017-06-29 10:45:11

标签: python-2.7 pandas python-datetime

我有一个对象列,其值为日期。我从csv读取后手动放置2016-08-31而不是NaN。

            close_date
0  1948-06-01 00:00:00   
1  2016-08-31 00:00:00   
2  2016-08-31 00:00:00   
3  1947-07-01 00:00:00   
4  1967-05-31 00:00:00

运行df['close_date'] = pd.to_datetime(df['close_date'])会导致

TypeError: invalid string coercion to datetime

添加coerce=True参数结果:

TypeError: to_datetime() got an unexpected keyword argument 'coerce'

此外,即使我调用列'close_date',数据帧中的所有列(一些int64,float64和datetime64 [ns])都会更改为dtype对象。

我做错了什么?

1 个答案:

答案 0 :(得分:9)

您需要errors='coerce'参数将一些不可解析的值转换为NaT

df['close_date'] = pd.to_datetime(df['close_date'], errors='coerce')
print (df)
  close_date
0 1948-06-01
1 2016-08-31
2 2016-08-31
3 1947-07-01
4 1967-05-31

print (df['close_date'].dtypes)
datetime64[ns]

但如果有一些混合值 - 数字与日期时间首先转换为str

df['close_date'] = pd.to_datetime(df['close_date'].astype(str), errors='coerce')
相关问题