-->

Convert R Matrix to Pandas Dataframe

2019-09-05 22:42发布

问题:

I'm trying to convert an R matrix to a pandas dataframe. I am using:

import pandas.rpy.common as com
df = com.convert_to_r_dataframe(r_matrix)

And I get:

TypeError: 'float' object cannot be interpreted as an index

Strangely enough this use case is omitted from all documentation I have come across. I would also settle for a conversion of the R matrix to a numpy array - since I will want to iterate over the rows anyway.

回答1:

Just use numpy.array():

from rpy2 import robjects
m = robjects.reval("matrix(1:6, nrow=2, ncol=3)")
import numpy as np
a = np.array(m)


回答2:

I think you are getting confused about the difference between convert_to_r_dataframe and convert_robj. Use the former one for converting TO R, and the latter one for converting BACK from R:

In [30]:
from rpy2 import robjects
m=robjects.r('matrix(1:6, nrow=2, ncol=3)')
In [31]:

print com.convert_robj(m)
   0  1  2
1  1  3  5
2  2  4  6
In [32]:

m=robjects.r('as.data.frame(matrix(1:6, nrow=2, ncol=3, dimnames=list(1:2, 1:3)))')
In [33]:

print com.convert_robj(m)
   1  2  3
1  1  3  5
2  2  4  6