[英]Conversion from rpy2 dataframe to pandas dataframe not working for columns of string type
If I try a conversion from pandas to R and back to pandas with a dataframe made only of numeric columns it goes ok, as can be seen below: If I try a conversion from pandas to R and back to pandas with a dataframe made only of numeric columns it goes ok, as can be seen below:
import pandas as pd
df_py = pd.DataFrame({'col1':[1,2,3,4,5],
'col2':[1.0,2.0,3.0,4.0,5.0]})
from rpy2.robjects.pandas2ri import py2ri
df_r = py2ri(df_py)
ri2py(df_r)
In this case, the result is:在这种情况下,结果是:
col1 col2
0 1 1.0
1 2 2.0
2 3 3.0
3 4 4.0
4 5 5.0
Now if I include a third column of string type I get an error.现在,如果我包含字符串类型的第三列,则会出现错误。 Look below:
往下看:
import pandas as pd
df_py = pd.DataFrame({'col1':[1,2,3,4,5],
'col2':[1.0,2.0,3.0,4.0,5.0],
'col3':['a','b','c','d','e']})
from rpy2.robjects.pandas2ri import py2ri
df_r = py2ri(df_py)
ri2py(df_r)
The error is:错误是:
/usr/local/lib/python3.6/dist-packages/numpy/core/_asarray.py in asarray(a, dtype, order)
83
84 """
---> 85 return array(a, dtype, copy=False, order=order)
86
87
ValueError: Buffer for this type not yet supported.
Is this a issue in rpy2 or is there something that I'm doing wrong?这是 rpy2 中的问题还是我做错了什么?
I got the lead for this answer from Parfait comment (see above).我从 Parfait 评论中得到了这个答案的线索(见上文)。
I changed the version of rpy2 in collab to 3.2.2 (latest version).我将collab中的rpy2版本改为3.2.2(最新版本)。
In this new version, the functions py2ri
and ri2py
have changed to py2rpy
and rpy2py
, respectively.在这个新版本中,函数
py2ri
和ri2py
已分别更改为py2rpy
和rpy2py
。
Using them in a code similar to the one presented in my question, the conversion back and forth happened perfectly.在类似于我的问题中提出的代码中使用它们,来回转换完美地发生了。
The code that I used is presented below:我使用的代码如下所示:
!pip install rpy2==3.2.2
import rpy2
import pandas as pd
df_py = pd.DataFrame({'col1':[1,2,3,4,5],
'col2':[1.0,2.0,3.0,4.0,5.0],
'col3':['a','b','c','d','e']})
from rpy2.robjects.pandas2ri import py2rpy, rpy2py
rpy2.robjects.pandas2ri.activate()
df_r = py2rpy(df_py)
rpy2py(df_r)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.