Last active
December 16, 2015 00:59
-
-
Save webbedfeet/5352113 to your computer and use it in GitHub Desktop.
pandas DataFrame to R data.frame conversion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import OrderedDict | |
import numpy as np | |
py2ri_orig = rpy2.robjects.conversion.py2ri | |
def conversion_pydataframe(obj): | |
if isinstance(obj, pandas.core.frame.DataFrame): | |
od = OrderedDict() | |
for name, values in obj.iteritems(): | |
if values.dtype.kind == 'O': | |
od[name] = rpy2.robjects.vectors.StrVector(values) | |
else: | |
od[name] = rpy2.robjects.conversion.py2ri(values) | |
return rpy2.robjects.vectors.DataFrame(od) | |
elif isinstance(obj, pandas.core.series.Series): | |
# converted as a numpy array | |
#res = original_conversion(obj) | |
res = np.array(obj) | |
# "index" is equivalent to "names" in R | |
if obj.ndim == 1: | |
res.names = ListVector({'x': ro.conversion.py2ri(obj.index)}) | |
else: | |
res.dimnames = ListVector(ro.conversion.py2ri(obj.index)) | |
return res | |
else: | |
return py2ri_orig(obj) | |
rpy2.robjects.conversion.py2ri = conversion_pydataframe |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment