Search code examples
pythonrpandasreticulate

how to write csv using pandas in R through reticulate?


I can read a csv in rstudio using reticulate. However I am not able to write it back.

> library(reticulate)
> pandas <- import("pandas")
> in.file <- pandas$read_csv(file.path(getwd(),"in.csv"))
> nrow(in.file)
[1] 504
> class(in.file)
[1] "data.frame"
> in.file<-r_to_py(in.file)
> class(in.file)
[1] "pandas.core.frame.DataFrame"        "pandas.core.generic.NDFrame"        "pandas.core.base.PandasObject"      "pandas.core.base.StringMixin"      
[5] "pandas.core.accessor.DirNamesMixin" "pandas.core.base.SelectionMixin"    "python.builtin.object"      

Solution

  • A pandas dataframe object has a to_csv attribute, but your in.file object was automatically converted to an R data.frame when being read in, so it does not have those attributes. In order to write the data frame back to a CSV using the Python method, you need to convert it to a Python object first using the r_to_py() function:

    infile_converted <- r_to_py(in.file)
    infile_converted$to_csv(file.path(getwd(), 'out.csv'))
    

    The other option would just be to use the native R function write.csv().