HDu*_*unn 2 python-2.7 python-datetime pandas
我有一个对象列,其值为日期.从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
Run Code Online (Sandbox Code Playgroud)
运行df['close_date'] = pd.to_datetime(df['close_date'])结果
TypeError: invalid string coercion to datetime
Run Code Online (Sandbox Code Playgroud)
添加coerce=True参数会导致:
TypeError: to_datetime() got an unexpected keyword argument 'coerce'
Run Code Online (Sandbox Code Playgroud)
此外,即使我调用列'close_date',数据帧中的所有列(一些int64,float64和datetime64 [ns])都会更改为dtype对象.
我究竟做错了什么?
jez*_*ael 10
您需要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]
Run Code Online (Sandbox Code Playgroud)
但是如果有一些混合值 - 带有日期时间的数字转换为str第一个:
df['close_date'] = pd.to_datetime(df['close_date'].astype(str), errors='coerce')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5172 次 |
| 最近记录: |