Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

python - Can I use rpy2 to save a pandas dataframe to an .Rdata file?

I never used rpy2 before, but I am just wondering if I could use it to save a python object (a pandas DataFrame) in an R-readable file. I am having trouble to move objects between these environments mainly because I'm using Windows and the data source is an Excel file. Yes, the kind that has cells with text including inverted commas, newlines, and all the stuff that CSV can't handle adequately.

I usually rely on XLConnectJars, but it seems to be broken

Installing package(s) into ‘C:/Program Files/R/library’
(as ‘lib’ is unspecified)
trying URL 'http://cran.csiro.au/bin/windows/contrib/2.15/XLConnectJars_0.2-4.zip'
Content type 'application/zip' length 16538311 bytes (15.8 Mb)
opened URL
downloaded 15.3 Mb

Warning in install.packages :
  downloaded length 16011264 != reported length 16538311

pandas reads it properly, but I need to use the information in R.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is how you write/read .RData files with rpy2 (since accepted solution is deprecated and doesn't show how to save to .RData file):

import rpy2
from rpy2 import robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()

# read .RData file as a pandas dataframe
def load_rdata_file(filename):
    r_data = robjects.r['get'](robjects.r['load'](filename))
    df = pandas2ri.ri2py(r_data)
    return df

# write pandas dataframe to an .RData file
def save_rdata_file(df, filename):
    r_data = pandas2ri.py2ri(df)
    robjects.r.assign("my_df", r_data)
    robjects.r("save(my_df, file='{}')".format(filename))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...