Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中显示每个单独变量的相关系数?_Python_Pandas - Fatal编程技术网

如何在Python中显示每个单独变量的相关系数?

如何在Python中显示每个单独变量的相关系数?,python,pandas,Python,Pandas,我运行了一个线性回归模型,得到了我的系数。如何在系数旁边打印变量 df = pd.read_csv('data', sep=";") reg = linear_model.LinearRegression() reg.fit(df[["age", "area", "bedrooms"]],df.price) print(reg.coef_) Output [ 6.55199614e-02 -1.86317709

我运行了一个线性回归模型,得到了我的系数。如何在系数旁边打印变量

df = pd.read_csv('data', sep=";")
reg = linear_model.LinearRegression()
reg.fit(df[["age", "area", "bedrooms"]],df.price)
print(reg.coef_)

Output 

[ 6.55199614e-02 -1.86317709e+00  2.20902007e-02]
我希望输出是

age coef: 6.55199614e-02
area coef: -1.86317709e+00
bedroom coef: 2.20902007e-02

如果您只想在系数旁边打印变量,您可以使用以下方法:

df=pd.read_csv('data',sep=“;”)
reg=线性模型。线性回归()
colnames=[“年龄”、“面积”、“卧室”]
注册适合度(df[colnames],df.price)
coefs_map=dict(zip(colnames,reg.coef_))
对于coefs_map.keys()中的k:
打印(f“{k}:{res[k]}”)
我相信
'\n'.join(col+'coef:'+str(coef)for(col,coef)in-zip(df.columns,reg.coef)
满足您的要求。但是,我推荐以下内容,因为它提供了更易于阅读的输出:

pad_length = 8+max(len(col) for col in df.columns)
output = '\n'.join((col+' coef: ').ljust(pad_length)+str(coef) for 
    (col, coef) in zip(df.columns, reg.coef_))

此外,所有这些都假设您的列名都已经是字符串。如果不是,你应该用
str(col)
替换
col

我的首选方法是
pd.Series(reg.coef,index=df.columns)
,然后免费打印。此外,使用
pd.Series
进行其他计算、通过
pd.concat进行模型比较等也更容易