Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pandas2ri - added named-vector-to-pandas conversion #887

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions rpy2/robjects/pandas2ri.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,9 +245,24 @@ def py2rpy_pandasseries(obj):
return res


def _ri2py_vector(obj):
x = numpy2ri.rpy2py(obj)
try:
# if names is assigned, convert to pandas series
return pandas.Series(x, obj.names)
except Exception:
# if dimnames assigned, convert to pandas dataframe
try:
rownames, colnames = obj.do_slot("dimnames")
x = pandas.DataFrame(x, index=rownames, columns=colnames)
finally:
# plain vector/matrix
return x


@rpy2py.register(SexpVector)
def ri2py_vector(obj):
res = numpy2ri.rpy2py(obj)
res = _ri2py_vector(obj)
return res


Expand All @@ -256,7 +271,7 @@ def rpy2py_floatvector(obj):
if POSIXct.isrinstance(obj):
return rpy2py(POSIXct(obj))
else:
return numpy2ri.rpy2py(obj)
return _ri2py_vector(obj)


@rpy2py.register(POSIXct)
Expand Down
16 changes: 16 additions & 0 deletions rpy2/tests/robjects/test_pandas_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,3 +518,19 @@ def test_ri2pandas_issue207(self):
if 'd' in robjects.globalenv:
del(robjects.globalenv['d'])
assert ok

def test_ri2pandas_named_vector(self):
rdataf = robjects.r("c('a' = 5, 'b' = 6, 'c' = 7, 'd' = 8)")
with localconverter(default_converter + rpyp.converter) as cv:
pandas_df = cv.rpy2py(rdataf)
assert all(x == y for x, y in zip(rdataf.names, pandas_df.index))

rdataf = robjects.r['matrix'](robjects.FloatVector([4, 5, 1, 10, 8, 3]),
nrow = 2, ncol = 3, byrow = True)
rdataf.rownames = robjects.StrVector(["Row 1", "Row 2"])
rdataf.colnames = robjects.StrVector(["Column 1", "Column 2", "Column 3"])
with localconverter(default_converter + rpyp.converter) as cv:
pandas_df = cv.rpy2py(rdataf)
assert all(x == y for x, y in zip(rdataf.rownames, pandas_df.index))
assert all(x == y for x, y in zip(rdataf.colnames, pandas_df.columns))

Loading