How to get data from R to pandas

萝らか妹 提交于 2019-12-10 18:47:06

问题


In a jupiter notebook I created some 2-d-list in R like

%%R
first <- "first"
second <- "second"

names(first) <- "first_thing"
names(second) <- "second_thing"

x <- list()
index <- length(x)+1
x[[index]] = first
x[[index +1]] = second

a %Rpull x does not return the nice representation but rather a ListVector. How can I convert it into something nicer e.g. a dict / pd.Dataframe? So far I had no luck following http://pandas.pydata.org/pandas-docs/stable/r_interface.html

edit

The list I want to convert is a 2-d list like results the updated code snipped from above


回答1:


Just slice the ListVector:

%Rpull x
pd.DataFrame(data=[i[0] for i in x], columns=['X'])

If you want a dictionary instead:

dict([[i,j[0]] for i,j in enumerate(x)])
{0: 'first', 1: 'first'}



回答2:


Since you created an R list (rather than, say, a data frame), the Python object returned is a ListVector.

R lists can have duplicated names, making the conversion to a dict something that cannot be guaranteed to be safe.

Should you feel lucky, and wanting a dict, it is rather straightforward. For example:

 from rpy2.robjects.vectors import ListVector
 l = ListVector({'a':1, 'b':2})
 d = dict(l.items())


来源:https://stackoverflow.com/questions/39593275/how-to-get-data-from-r-to-pandas

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