import pandas as pd import rpy2.robjects as ro from rpy2.robjects.packages import importr from rpy2.robjects import pandas2ri from rpy2.robjects.conversion import localconverter pd_df = pd.DataFrame({'int_values': [1,2,3],'str_values': ['abc', 'def', 'ghi']}) print(pd_df) int_values str_values 0 1 abc 1 2 def 2 3 ghi with localconverter(ro.default_converter + pandas2ri.converter): r_from_pd_df = ro.conversion.py2rpy(pd_df) print(r_from_pd_df) int_values str_values 0 1 abc 1 2 def 2 3 ghi # 1. The conversion is automatically happening when calling R functions. For example, when calling the R function , base::summary base = importr('base') with localconverter(ro.default_converter + pandas2ri.converter): df_summary = base.summary(pd_df) #自动转换 print(df_summary) # ['Min. :1.0 ' '1st Qu.:1.5 ' 'Median :2.0 ' 'Mean :2.0 ' '3rd Qu.:2.5 ' 'Max. :3.0 ' 'Length:3 ' 'Class :character ' 'Mode :character ' NA_character_ NA_character_ NA_character_] # 2. Note that a ContextManager is used to limit the scope of the conversion. Without it, rpy2 will not know how to convert a pandas data frame: try: df_summary = base.summary(pd_df) except NotImplementedError as nie: print('NotImplementedError:') print(nie)