Reading R dataframes in python in Jupyter

Viewed 182

I want to read R objects back to python in Jupyter. For example, in Jupyter this example reads a dataframe generated in python and processed in R. Now I process this dataframe and create a new one that I want to be able to read to python.

Python cell:

# enables the %%R magic, not necessary if you've already done this
%load_ext rpy2.ipython

import pandas as pd
df = pd.DataFrame({
    'cups_of_coffee': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    'productivity': [2, 5, 6, 8, 9, 8, 0, 1, 0, -1]
})

R cell:

%%R -i df 
# import df from global environment

df$time = 1
df_new = df
df_new

If I move to a new cell the new dataframe df_new cannot read it as is not recognized.

I tried this:

%Rget df_new

But don't know how to assign it to a pandas dataframe or pass it to a python function.

How can switch back to a python cell and be able to read this new dataframe created in the R cell?

1 Answers

So, I randomly tried something myself and it worked. I couldn't find some good documentation.

So, one can just simply do:

df_python = %Rget df_new

This worked for me.

Related