2016-08-23 52 views
4

MY指數的日期時間字符串格式'%m/%d/%Y' ('09/26/2007')轉換「%M /%d /%Y」串索引到大熊貓的日期時間指數

當我嘗試使用pd.to_datetime功能pd.to_datetime(df.index)到指數轉換成日期時間指數,我得到了錯誤消息OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00

它看起來像大熊貓無法檢測到正確的字符串格式,我怎麼可以將索引轉換爲日期時間索引?

感謝

+0

的'pd.to_datetime()'可以檢測到這種格式。其實我有一行缺少索引,這會導致錯誤。檢查接受的答案。 – user5025141

回答

4

的錯誤消息的樣子,看來你可能有串'1/1/0001'您的索引。例如,

df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001']) 
pd.to_datetime(df.index) 

引發

OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00 

此錯誤的出現是因爲DatetimeIndex使用NumPy的datetime64[ns] S的不能代表日期0001-01-01的陣列。 dtype只能表示dates in the range [1678 AD, 2262 AD]

有一個pandas github issue討論這個限制。

目前,推薦的解決方案是使用一個PeriodIndex代替DatetimeIndex的:

df = pd.DataFrame([1,2], index=['09/26/2007', '1/1/0001']) 
df.index = pd.PeriodIndex(df.index, freq='D') 

產生

  0 
2007-09-26 1 
1-01-01  2 
+0

我試過'df [df.index =='1/1/0001']',它是空的。我不知道我怎麼能找到那個不好的約會,因爲它不應該存在。 – user5025141

+0

嘗試'df ['dates'] = pd.to_datetime(df.index,errors ='coerce')'。 (這會將無效字符串轉換爲'NaT'(非一次性)對象。)然後查看'df.loc [pd.isnull(df ['dates'])]''。 – unutbu

+0

謝謝!我發現那個日期,它錯過了日期。該行的索引是空的。處理完它後,'pd.to_datetime()'完美無缺。非常感謝! – user5025141