2014-01-23 65 views
3

我已經嘗試用(熊貓)pd.ols和(statsmodels)sm.ols得到迴歸散點圖與迴歸線,我可以得到散點圖,但我似乎無法得到參數來得到迴歸線的情節。這可能是顯而易見的,我做了一些剪切和粘貼編碼這裏:-((使用此作爲指南:http://nbviewer.ipython.org/github/weecology/progbio/blob/master/ipynbs/statistics.ipynb獲取迴歸線從熊貓迴歸繪圖

我的數據是在數據框大熊貓和X列merged2 [: - 1] .lastqu 而y數據列merged2 [: - 1] .Units 我的代碼如下內容: 得到迴歸:

def fit_line2(x, y): 
    X = sm.add_constant(x, prepend=True) #Add a column of ones to allow the calculation of the intercept 
    model = sm.OLS(y, X,missing='drop').fit() 
    """Return slope, intercept of best fit line.""" 
    X = sm.add_constant(x) 
    return model 
model=fit_line2(merged2[:-1].lastqu,merged2[:-1].Units) 
print fit.summary() 

^^^^似乎確​​定

intercept, slope = model.params << I don't think this is quite right 
plt.plot(merged2[:-1].lastqu,merged2[:-1].Units, 'bo') 
plt.hold(True) 

^^ ^^^這得到了散點圖 * *和下面沒有得到我的迴歸線

x = np.array([min(merged2[:-1].lastqu), max(merged2[:-1].lastqu)]) 
y = intercept + slope * x 
plt.plot(x, y, 'r-') 
plt.show() 

數據幀的SNIPPIT:所述[:-1]消除了數據中的當前週期隨後將是一個投影

Units lastqu Uperchg lqperchg fcast errpercent nfcast 
date        
2000-12-31 7177 NaN  NaN  NaN  NaN  NaN  NaN 
2001-12-31 10694 2195.000000  0.490038 NaN  10658.719019 1.003310 NaN 
2002-12-31 11725 2469.000000 

編輯:

我發現我可以這樣做:

fig = plt.figure(figsize=(12,8)) 
fig = sm.graphics.plot_regress_exog(model, "lastqu", fig=fig) 

這裏描述的Statsmodels doc 這似乎得到了我想要的主要事情(還有更多)我仍然想知道我在之前的代碼中出錯的地方!

+0

有什麼問題或問題?從閱讀例子來看,一切看起來都是正確的。 – user333700

+0

剩下的問題是我如何得到一個簡單的迴歸線,使用代碼「類似於x = np.array序列上面它不起作用?(沒有錯誤,只是沒有行)雖然我可以從sm.graphics .plot – dartdog

回答

1

檢查你的數組和變量有什​​麼值。

我的猜測是你的x只是nans,因爲你使用Python的min和max。至少在我目前打開的熊貓版本中會發生這種情況。

最小值和最大值的方法應該工作,因爲他們知道如何處理nan S或遺漏值

>>> x = pd.Series([np.nan,2], index=['const','slope']) 
>>> x 
const NaN 
slope  2 
dtype: float64 

>>> min(x) 
nan 
>>> max(x) 
nan 

>>> x.min() 
2.0 
>>> x.max() 
2.0 
+1

所以我確實截取了斜率= model.params plt.plot(merged2 [: - 1] .lastqu,merged2 [: - 1] .Units,'bo') plt.hold(True) x = np.array([merged2 [: - 1] .lastqu.min(),merged2 [: - 1] .lastqu.max()]) y =截距+斜率* x plt.plot(x,y,' ') plt.show() – dartdog