2017-09-13 48 views
0

使用pandas读取.csv文件,然后使用rpy2软件包将其转换为R数据框后,我使用一些R函数(也通过rpy2)创建了一个模型,现在想要对模型进行摘要并将其转换为Pandas数据框(以便我可以将其保存为.csv文件或将其用于其他目的)。为了弄清楚:如何将rpy2矩阵对象转换为Pandas数据框?

import pandas as pd 
from rpy2.robjects import r 
import sys 
import rpy2.robjects.packages as rpackages 
from rpy2.robjects.vectors import StrVector 
from rpy2.robjects import r, pandas2ri 

pandas2ri.activate() 
caret = rpackages.importr('caret') 
broom= rpackages.importr('broom') 

my_data= pd.read_csv("my_data.csv") 
r_dataframe= pandas2ri.py2ri(my_data) 

preprocessing= ["center", "scale"] 
center_scale= StrVector(preprocessing) 

#these are the columns in my data frame that will consist of my predictors in the model 
predictors= ['predictor1','predictor2','predictor3'] 
predictors_vector= StrVector(predictors) 

#this column from the dataframe consists of the outcome of the model 
outcome= ['fluorescence'] 
outcome_vector= StrVector(outcome) 

#this line extracts the columns of the predictors from the dataframe 
columns_predictors= r_dataframe.rx(True, columns_vector) 

#this line extracts the column of the outcome from the dataframe 
column_response= r_dataframe.rx(True, column_response) 

cvCtrl = caret.trainControl(method = "repeatedcv", number= 20, repeats = 100) 

model_R= caret.train(columns_predictors, columns_response, method = "glmStepAIC", preProc = center_scale, trControl = cvCtrl) 

summary_model= base.summary(model_R) 

coefficients= stats.coef(summary_model) 

pd_dataframe = pandas2ri.ri2py(coefficients) 

pd_dataframe.to_csv("coefficents.csv") 

虽然这个工作流程表面上是正确的,输出的.csv文件没有满足我的需求:

我也跟着出去(https://pandas.pydata.org/pandas-docs/stable/r_interface.html源)对大熊猫站点上的说明,因为列和行的名称已被删除。当我运行命令type(pd_dataframe)时,我发现它是一个<type 'numpy.ndarray'>。虽然表格的信息仍然存在,但新的格式已经删除了列和行的名称。

所以我运行命令type(coefficients),发现它是一个<class 'rpy2.robjects.vectors.Matrix'>。由于这个Matrix对象仍然保留着我的列和行的名字,我试图将它转换成一个R对象DataFrame,但是我的努力被证明是徒劳的。此外,我不知道为什么行pd_dataframe = pandas2ri.ri2py(coefficients)没有产生一个熊猫DataFrame对象,也不知道为什么它不保留我的列和行的名称。

任何人都可以推荐一种方法,这样我可以得到某种熊猫DataFrame保留我的列和行的名称?

UPDATE

的新方法是在一个稍微较旧版本称为pandas2ri.ri2py_dataframe(来源:​​)封装的文件中提到,现在我有一个适当的数据帧,而不是numpy的阵列。但是,我仍然无法正确传输行和列的名称。有什么建议么?

+0

目前,当前版本的文档位于https://rpy2.github.io/doc/v2.9.x/html/index .html – lgautier

+0

@lgautier我知道,但我使用的版本是2.8.x,因为当我尝试下载和使用2.9.x时,我的IDE说我的Python 2.7脚本是不兼容的,它只能用于Python 3。 X。 –

回答