使用pandas数据帧进行线性回归的推荐方法是什么(如果有的话)?我可以做到,但我的方法似乎非常精细。我做的事情是不必要的复杂吗?
R代码,用于比较:
x <- c(1,2,3,4,5)
y <- c(2,1,3,5,4)
M <- lm(y~x)
summary(M)$coefficients
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.6 1.1489125 0.522233 0.6376181
x 0.8 0.3464102 2.309401 0.1040880
现在,我的python(2.7.10),rpy2(2.6.0)和pandas(0.16.1) 版本:
import pandas
import pandas.rpy.common as common
from rpy2 import robjects
from rpy2.robjects.packages import importr
base = importr('base')
stats = importr('stats')
dataframe = pandas.DataFrame({'x': [1,2,3,4,5],
'y': [2,1,3,5,4]})
robjects.globalenv['dataframe']\
= common.convert_to_r_dataframe(dataframe)
M = stats.lm('y~x', data=base.as_symbol('dataframe'))
print(base.summary(M).rx2('coefficients'))
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.6 1.1489125 0.522233 0.6376181
x 0.8 0.3464102 2.309401 0.1040880
顺便说一下,我确实在导入pandas.rpy.common
时获得了FutureWarning。但是,当我尝试pandas2ri.py2ri(dataframe)
将数据帧从pandas转换为R(如上所述here)时,我得到了
NotImplementedError: Conversion 'py2ri' not defined for objects of type '<class 'pandas.core.series.Series'>'
答案 0 :(得分:23)
调用pandas2ri.activate()
后,会自动从Pandas对象到R对象进行一些转换。例如,您可以使用
M = R.lm('y~x', data=df)
而不是
robjects.globalenv['dataframe'] = dataframe
M = stats.lm('y~x', data=base.as_symbol('dataframe'))
import pandas as pd
from rpy2 import robjects as ro
from rpy2.robjects import pandas2ri
pandas2ri.activate()
R = ro.r
df = pd.DataFrame({'x': [1,2,3,4,5],
'y': [2,1,3,5,4]})
M = R.lm('y~x', data=df)
print(R.summary(M).rx2('coefficients'))
产量
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.6 1.1489125 0.522233 0.6376181
x 0.8 0.3464102 2.309401 0.1040880
答案 1 :(得分:13)
R和Python并不完全相同,因为您在Python / rpy2中构建数据框,而在R中使用向量(没有数据框)。
否则,使用rpy2
的转换付款似乎在此处运行:
from rpy2.robjects import pandas2ri
pandas2ri.activate()
robjects.globalenv['dataframe'] = dataframe
M = stats.lm('y~x', data=base.as_symbol('dataframe'))
结果:
>>> print(base.summary(M).rx2('coefficients'))
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.6 1.1489125 0.522233 0.6376181
x 0.8 0.3464102 2.309401 0.1040880
答案 2 :(得分:2)
我可以通过概述如何检索系数表的特定元素来添加unutbu's answer,其中包括 p - 值。
def r_matrix_to_data_frame(r_matrix):
"""Convert an R matrix into a Pandas DataFrame"""
import pandas as pd
from rpy2.robjects import pandas2ri
array = pandas2ri.ri2py(r_matrix)
return pd.DataFrame(array,
index=r_matrix.names[0],
columns=r_matrix.names[1])
# Let's start from unutbu's line retrieving the coefficients:
coeffs = R.summary(M).rx2('coefficients')
df = r_matrix_to_data_frame(coeffs)
这给我们留下了一个DataFrame,我们可以通过这种方式访问:
In [179]: df['Pr(>|t|)']
Out[179]:
(Intercept) 0.637618
x 0.104088
Name: Pr(>|t|), dtype: float64
In [181]: df.loc['x', 'Pr(>|t|)']
Out[181]: 0.10408803866182779