2017-06-22 61 views
0

我通常會從某個csv文件中調用數據,並使用pandas.to_datetime函數將日期列更改爲datetime格式以供進一步的數據處理。python pandas to_datetime無法穩定工作

但是,有時to_datetime函數有效,有時不會。 它不穩定工作,我通常使用大量的時間來調整數據時間格式..

我嘗試了很多方法,但他們都不穩定工作。 請有人請幫助我解決這個問題?

df1 = pd.read_csv("somefile.csv", encoding='utf-8', parse_dates=[0]) 
# the result turns out that the parse_dates does not work at all here 

df1["Date"]= df1["Date"].apply(pd.to_datetime) 
# after this change, the type(df1["Date"][0]) becomes pandas._libs.tslib.Timestamp 

df1["Date"] = df1["Date"].dt.date.apply(lambda x: datetime.date(x.year,x.month,x.day)) 
# this code worked yesterday but not today anymore... 
# TypeError: descriptor 'date' requires a 'datetime.datetime' object but received a 'int' 

錯誤代碼在這裏說,「描述‘日期’需要‘datetime.datetime’對象,但獲得了‘廉政’」 我想的DF [「日」]類型更改爲datetime型而不是時間戳。

我的熊貓數據框看起來像這樣(只有日期列中顯示) 的原始數據在這裏提供:https://www.dropbox.com/s/rrhy9my9yp1gy2y/test.csv?dl=0

Date 
2015-01-07 
2015-01-08 
2015-01-09 
2015-01-10 
2015-01-11 

我的Python版本是2.7 很沮喪這個問題一段時間, 人們除了我everyones to_datetime函數運行良好?

+0

這將有助於如果你能後的原始數據,並證明你爲什麼認爲它不起作用 – EdChum

+0

請看到錯誤消息Typ eError:描述符'date'需要'datetime.datetime'對象,但收到'int'。我只能將數據轉換爲時間戳,而不是日期時間 –

+0

再次請求您提供原始數據和代碼,以再現您的問題,'read_csv'的parse_dates' arg可以將多個列解析爲'datetime','pd.to_datetime'也相當強勁。編輯你的問題與數據,代碼,期望的輸出和錯誤 – EdChum

回答

1

你需要刪除apply,只需要Series.dt.date

df1 = pd.read_csv('test.csv', parse_dates=[0]) 

df1["Date"] = df1["Date"].dt.date.apply(lambda x: datetime.date(x.year,x.month,x.day)) 

到:

df1["Date"] = df1["Date"].dt.date 

print (type(df1.loc[0, 'Date'])) 
<class 'datetime.date'> 

但如果需要的元組:

df1["Date"] = df1["Date"].dt.date.apply(lambda x: (x.year,x.month,x.day)) 
print (df1.head()) 
      Date trend 
0 (2015, 1, 7)  37 
1 (2015, 1, 8)  37 
2 (2015, 1, 9)  37 
3 (2015, 1, 10)  37 
4 (2015, 1, 11)  38