Skip to content

Instantly share code, notes, and snippets.

@chilampoon
Last active July 3, 2022 15:46
Show Gist options
  • Save chilampoon/89502199c632cfc5cac7b727c9a92180 to your computer and use it in GitHub Desktop.
Save chilampoon/89502199c632cfc5cac7b727c9a92180 to your computer and use it in GitHub Desktop.
Convert dataframes of R & Python using rpy2 in jupyter
# ------ a python cell ------
%load_ext rpy2.ipython
pd_df = pd_df.T
# ------ an R cell ------
%%R -i pd_df
# `-i pd_df` means access to the global variable pd_df
r_df = do.something(pd_df)
## ------ another python cell ------
# r object back to python (pandas df)
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
res = ro.r['r_df']
with localconverter(ro.default_converter + pandas2ri.converter):
pd_df_2 = ro.conversion.rpy2py(res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment