【问题标题】:How to convert a rpy2 matrix object into a Pandas data frame?如何将 rpy2 矩阵对象转换为 Pandas 数据框?
【发布时间】:2018-02-22 08:35:39
【问题描述】:

在使用 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'>。虽然表格的信息仍然存在,但新的格式已经删除了列和行的名称。

于是我运行了命令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 数组。但是,我仍然无法正确传输行和列的名称。有什么建议吗?

【问题讨论】:

  • 目前,当前版本的文档位于rpy2.github.io/doc/v2.9.x/html/index.html
  • @lgautier 我知道,但我使用的是 2.8.x 版本,因为当我尝试下载和使用 2.9.x 时,我的 IDE 说我的 Python 2.7 脚本不兼容,它只会使用 Python 3.x。

标签: python-2.7 pandas rpy2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多