2016-10-24 50 views
1

我有兩個問題,我相信都發布到日期格式。分散和線性迴歸的日期問題

我有日期和值的CVS:

2012-01-03 00:00:00  95812  
2012-01-04 00:00:00 101265 
... 
2016-10-21 00:00:00  93594 

後,我與read_csv我試圖解析的日期加載:

X.Dated = pd.to_datetime(X.Dated, format='%Y-%m-%d %H:%M:%S', errors='raise') 

我也試圖與:

dateparse = lambda x: pd.datetime.strptime(x, '%Y-%m-%d %H:%M:%S') 
X = pd.read_csv('sales.csv', parse_dates=['Dated'], date_parser=dateparse) 

infer_datetime_format的說法。

所有這些似乎工作正常,因爲當我打印出來的日期看起來像這樣:2012-01-03

問題出現,當我想要繪製在圖表的數據,該行:

ax.scatter(X.Dated, X.Val, c='green', marker='.') 

給我一個錯誤:

TypeError: invalid type promotion 

而且當我嘗試用線性迴歸使用()算法擬合命令 工作正常,但得分和預測給了我這個錯誤:

TypeError: Cannot cast array data from dtype('<M8[ns]') to dtype('float64') according to the rule 'safe' 

我嘗試了很多事情來解決它,但沒有運氣。 任何幫助,將不勝感激。

回答

5

ax.scatter(目前)不接受熊貓系列,但它可以接受大熊貓時間戳列表(例如X['Dated'].tolist()),或D型datetime64[ns](如X['Dated'].values)的NumPy的數組:

import pandas as pd 
import matplotlib.pyplot as plt 

X = pd.DataFrame({'Dated': [pd.Timestamp('2012-01-03 00:00:00'), 
          pd.Timestamp('2012-01-04 00:00:00'), 
          pd.Timestamp('2016-10-21 00:00:00')], 
        'Val': [95812, 101265, 93594]}) 

fig, ax = plt.subplots() 
# ax.scatter(X['Dated'].tolist(), X['Val'], c='green', marker='.', s=200) 
ax.scatter(X['Dated'].values, X['Val'], c='green', marker='.', s=200) 
plt.show() 

enter image description here


Under the hood, the ax.scatter method calls

x = self.convert_xunits(x) 
y = self.convert_yunits(y) 

來處理類似日期的輸入。 convert_xunits將NumPy datetime64數組轉換爲Matplotlib datenums,但它將Pandas時間序列轉換爲NumPy datetime64數組。

所以,當一個時間序列熊貓被作爲輸入傳遞到ax.scatter,代碼最終失敗時this line is reached

offsets = np.dstack((x, y)) 

np.dstack試圖促進其輸入的dtypes到一個共同的D型。如果x具有D型datetime64[ns]y具有D型float64,然後

TypeError: invalid type promotion 

上升,因爲沒有本地NumPy的D類是既兼容。

+0

感謝它的幫助,我現在可以在圖表上顯示它。這回答了我的問題的第一部分。你知道爲什麼我有另一個錯誤:根據規則'安全',無法將數組數據從dtype(' Greg

+0

@Greg:我補充了一些關於錯誤來自何處的解釋。最終,當np.dstack試圖將x和y輸入組合到一個數組中時(通常使用dtype),會引發TypeError。由於'datetime64 [ns]'和'float' dtypes沒有兼容的公共dtype,所以會引發TypeError。 – unutbu