如何将 rpy2 矩阵对象转换为 Pandas 数据框?

How to convert a rpy2 matrix object into a Pandas data frame?

在使用 pandas 读取 .csv 文件,然后使用 rpy2 包将其转换为 R 数据帧之后,我使用一些 R 函数(也通过 rpy2)创建了一个模型,现在我想获取模型的摘要并将其转换为 Pandas 数据框(以便我可以将其保存为 .csv 文件或将其用于其他目的)。

我已按照 pandas 网站(来源:https://pandas.pydata.org/pandas-docs/stable/r_interface.html)上的说明进行操作以弄清楚:

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 文件不符合我的需要,因为列名和行名被删除了。当我运行命令type(pd_dataframe)时,我发现它是一个<type 'numpy.ndarray'>。尽管 table 的信息仍然存在,但新格式已删除列和行的名称。

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

任何人都可以推荐一种方法,以便我可以获得某种 pandas DataFrame 来保留我的列和行的名称吗?

更新

在稍旧版本的包的文档中提到了一种新方法,称为 pandas2ri.ri2py_dataframe(来源:https://rpy2.readthedocs.io/en/version_2.7.x/changes.html),现在我有一个合适的数据框而不是 numpy 数组.但是,我仍然无法正确获取行和列的名称 t运行sferred。有什么建议吗?

可能它应该在转换过程中自动发生,但同时可以很容易地从 R 对象中获取行名和列名并将其添加到 pandas DataFrame。例如,R 矩阵的列名应位于:https://rpy2.github.io/doc/v2.9.x/html/vector.html#rpy2.robjects.vectors.Matrix.colnames