Convert R Matrix to Pandas Dataframe

独自空忆成欢 提交于 2019-12-25 04:19:33

问题


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


来源:https://stackoverflow.com/questions/24729010/convert-r-matrix-to-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!