2017-06-29 28 views
1

我有一個值爲日期的對象列。我從csv閱讀後手動放置2016-08-31而不是NaN。爲什麼pd.to_datetime無法轉換?

  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對象。

我在做什麼錯?

回答

3

你需要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') 
相關問題