2013-02-18 46 views
3

我想知道是否可以將pandas.ols模型同時應用於多個響應變量的數據框。同時在多個因變量上使用pandas.ols

所以,想象一下,我有以下:

In [109]: y=pandas.DataFrame(np.random.randn(10,4)) 
In [110]: x=pandas.DataFrame(np.random.randn(10,1)) 

我願做這樣的事情:

In [111]: model=pandas.ols(y=y, x=x) 

基本上有四個模型輸出結果或係數至少訪問四個。如果可能,我寧願避免通過響應變量循環。

+0

你只需要做OLS沒有特殊的標準錯誤? – BKay 2013-04-12 17:54:05

回答

1

我認爲這應該做到這一點。

#First generate the data 
x=pd.DataFrame(np.random.randn(10,1)) 
y=pd.DataFrame(np.random.randn(10,4)) 

#Since we are doing things manually we'll need to add the constant term to the x matrix 
x[1] = ones(10) 

#This matrix precomputes (X'X)^-1X which we will premultiply the y matrix by to get results 
tmpmat = np.dot(np.linalg.pinv(np.dot(x.T ,x)),x.T) 

#Solve for the betas 
betamatrix = np.dot(tmpmat,y) 

#Compare with the pandas output one at a time. 
model=pd.ols(y=y[0], x=x, intercept=False) 
model=pd.ols(y=y[1], x=x, intercept=False) 
0

已經做了這麼多次,還沒有找到循環的替代方案。以下代碼會將這四個迴歸的結果存儲在一個字典中。如果你只對一些係數感興趣,你可以在循環迴歸時捕獲它們。

model = {} 
for i in y: 
    model[i] = pd.ols(y=y[i], x=x)