pandas 为什么 pd.to_datetime 无法转换?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44823001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
why does pd.to_datetime fail to convert?
提问by HDunn
I have an object column with values which are dates. I manually placed 2016-08-31 instead of NaN after reading from csv.
我有一个对象列,其值为日期。从 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
Running df['close_date'] = pd.to_datetime(df['close_date'])
results in
运行df['close_date'] = pd.to_datetime(df['close_date'])
结果
TypeError: invalid string coercion to datetime
Adding coerce=True
argument results in:
添加coerce=True
参数导致:
TypeError: to_datetime() got an unexpected keyword argument 'coerce'
Furthermore, even though I call the column 'close_date', all the columns in the dataframe, some int64, float64, and datetime64[ns], change to dtype object.
此外,即使我将列称为“close_date”,数据框中的所有列,一些 int64、float64 和 datetime64[ns],也会更改为 dtype 对象。
What am I doing wrong?
我究竟做错了什么?
回答by jezrael
You need errors='coerce'
parameter what convert some not parseable values to NaT
:
您需要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]
But if there are some mixed values - numeric with datetimes convert to str
first:
但是如果有一些混合值 - 日期时间的数字转换为str
第一个:
df['close_date'] = pd.to_datetime(df['close_date'].astype(str), errors='coerce')