我想将r数据框转换为pandas数据框,请考虑以下代码作为示例
import rpy2, rpy2.robjects as robjects, rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
import os
from rpy2.robjects.packages import importr
base = importr('base')
print(base.R_home())
# install packages in r from python
packageNames = ('ggplot2', 'hexbin', 'MVN','afex', 'emmeans')
utils = rpackages.importr('utils')
utils.chooseCRANmirror(ind=1)
packnames_to_install = [x for x in packageNames if not rpackages.isinstalled(x)]
if len(packnames_to_install) > 0:
utils.install_packages(StrVector(packnames_to_install))
# Read table function in r to python dataframe
data = robjects.r('read.table(file =' \
'"http://personality-project.org/r/datasets/R.appendix3.data", header = T)')
data.head()
我想将此数据框转换为python数据框
如下
# Convert R Dataframe to python Dataframe
# !pip install tzlocal
# type(data)
from rpy2.robjects import pandas2ri
pd_df = pandas2ri.ri2py_dataframe(data)
pd_df
我收到以下错误
TypeError: Parameter 'categories' must be list-like, was <rpy2.rinterface.StrSexpVector - Python:0x0000021E88AB4FC0 / R:0x0000021EF1A6AE98>
如何使其正常工作?
答案 0 :(得分:0)
import rpy2, rpy2.robjects as robjects, rpy2.robjects.packages as rpackages
from rpy2.robjects.vectors import StrVector
#Converting data frames back and forth between rpy2 and pandas
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
import os
from rpy2.robjects.packages import importr
base = importr('base')
data = robjects.r('read.table(file =' \
'"http://personality-project.org/r/datasets/R.appendix3.data", header = T)')
data.head()
从rpy2.robjects导入r,pandas2ri
pandas2ri.activate()
在rpy2和pandas之间来回转换数据帧