pandas -如何将R数据框转换回 pandas ? [英] Pandas - how to convert r dataframe back to pandas?

查看:81
本文介绍了 pandas -如何将R数据框转换回 pandas ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下命令将pandas df转换为r:

I converted a pandas df to r using the the below:

import pandas as pd
import pandas.rpy.common as com
import rpy2.robjects as ro
from rpy2.robjects.packages import importr
rdf = com.convert_to_r_dataframe(df)

如何将rdf转换回熊猫df?

How do I convert rdf back to a pandas df?

df = f(rdf) ?

推荐答案

自rpy2 2.4.0版开始,作为可选模块包括了在rpy2pandas之间来回转换数据帧.有了它,无需显式转换,它将很快完成.

Since rpy2 release 2.4.0 converting data frames back and forth between rpy2 and pandas is included as an optional module. With it, no need to convert explicitly, it will be done on the fly.

该文档包含示例(也可作为Jupyter笔记本获得-页面顶部附近的链接): https://rpy2.github.io/doc/Latest/html/pandas.html#interoperability-with-pandas

The documentation contains examples (also available as a Jupyter notebook - link available near the top of the page): https://rpy2.github.io/doc/latest/html/pandas.html#interoperability-with-pandas

注意:该问题的原始答案如下.

Note: The original answer to this question recommended the following.

from rpy2.robjects import pandas2ri
pandas2ri.activate()

如果出于任何原因希望进行显式转换,则函数为pandas2ri.py2ri()pandas2ri.ri2py()(它们分别为pandas2ri.pandas2ri()pandas2ri.ri2pandas()).

If wishing to convert explicitly for any reason, the functions are pandas2ri.py2ri() and pandas2ri.ri2py() (they were pandas2ri.pandas2ri() and pandas2ri.ri2pandas()).

注意:自rpy2版本3.3.0起,显式转换如下进行

Note: Since rpy2 release 3.3.0 explicit conversion is done as follows

import rpy2.robjects as ro

dt = pd.DataFrame()
# To R DataFrame
r_dt = ro.conversion.py2rpy(dt)
# To pandas DataFrame
pd_dt = ro.conversion.rpy2py(r_dt)

有关更多详细信息,请查看此链接.

For more details check out this link.

这篇关于 pandas -如何将R数据框转换回 pandas ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆