问题描述
我正在尝试将 R 代码的一部分转换为 Python.在这个过程中,我遇到了一些问题.
I am trying to convert one part of R code in to Python. In this process I am facing some problems.
我有一个 R 代码,如下所示.在这里,我以 .rdata 格式保存我的 R 输出.
I have a R code as shown below. Here I am saving my R output in .rdata format.
nms <- names(mtcars)
save(nms,file="mtcars_nms.rdata")
现在我必须将 mtcars_nms.rdata 加载到 Python 中.我导入了 rpy2 模块.然后我尝试将文件加载到 python 工作区中.但无法看到实际输出.
Now I have to load the mtcars_nms.rdata into Python.I imported rpy2 module. Then I tried to load the file into python workspace. But could not able to see the actual output.
我使用以下python代码导入.rdata.
I used the following python code to import the .rdata.
import pandas as pd
from rpy2.robjects import r,pandas2ri
pandas2ri.activate()
robj = r.load('mtcars_nms.rdata')
robj
我的python输出是
My python output is
R object with classes: ('character',) mapped to:
<StrVector - Python:0x000001A5B9E5A288 / R:0x000001A5B9E91678>
['mtcars_nms']
现在我的目标是从 mtcars_nms 中提取信息.
Now my objective is to extract the information from mtcars_nms.
在 R 中,我们可以使用
In R, we can do this by using
load("mtcars_nms.rdata");
get('mtcars_nms')
现在我想用 Python 做同样的事情.
Now I wanted to do the same thing in Python.
推荐答案
有一个新的 python 包 pyreadr 这使得将 RData 和 Rds 文件导入 python 变得非常容易:
There is a new python package pyreadr that makes very easy import RData and Rds files into python:
import pyreadr
result = pyreadr.read_r('mtcars_nms.rdata')
mtcars = result['mtcars_nms']
它不依赖于安装了 R 或其他外部依赖项.它是 C 库 librdata 的包装器,因此速度非常快.
It does not depend on having R or other external dependencies installed.It is a wrapper around the C library librdata, therefore it is very fast.
您可以使用 pip 非常轻松地安装它:
You can install it very easily with pip:
pip install pyreadr
repo 在这里:https://github.com/ofajardo/pyreadr
免责声明:我是开发者.
Disclaimer: I am the developer.
这篇关于如何将 R 的 .rdata 文件加载到 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!