This code manually selects a column from the y table and then joins it to the X table. The program then performs linear regression. Any idea how to do this for every single column from the y table?
JavaScript
x
14
14
1
yDF = pd.read_csv('ytable.csv')
2
yDF.drop('Dates', axis = 1, inplace = True)
3
XDF = pd.read_csv('Xtable.csv')
4
ycolumnDF = yDF.iloc[:,0].to_frame()
5
regressionDF = pd.concat([XDF,ycolumnDF], axis=1)
6
7
X = regressionDF.iloc[:,1:20]
8
y = regressionDF.iloc[:,20:].squeeze()
9
10
lm = linear_model.LinearRegression()
11
lm.fit(X,y)
12
cf = lm.coef_
13
print(cf)
14
Advertisement
Answer
You can regress multiple y’s on the same X’s at the same time. Something like this should work
JavaScript
1
10
10
1
import numpy as np
2
from sklearn.linear_model import LinearRegression
3
4
df_X = pd.DataFrame(columns = ['x1','x2','x3'], data = np.random.normal(size = (10,3)))
5
df_y = pd.DataFrame(columns = ['y1','y2'], data = np.random.normal(size = (10,2)))
6
X = df_X.iloc[:,:]
7
y = df_y.iloc[:,:]
8
lm = LinearRegression().fit(X,y)
9
print(lm.coef_)
10
produces
JavaScript
1
3
1
[[ 0.16115884 0.08471495 0.39169592]
2
[-0.51929011 0.29160846 -0.62106353]]
3
The first row here ([ 0.16115884 0.08471495 0.39169592]
) are the regression coefs of y1
on xs and the second are the regression coefs of y2
on xs.