【问题标题】:how to write csv using pandas in R through reticulate?如何通过网状在R中使用熊猫编写csv?
【发布时间】:2019-10-05 01:32:20
【问题描述】:

我可以使用 reticulate 在 rstudio 中读取 csv。但是我无法将其写回。

> 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"      

【问题讨论】:

    标签: python r pandas reticulate


    【解决方案1】:

    pandas 数据框对象具有to_csv 属性,但您的in.file 对象在读入时会自动转换为R data.frame,因此它没有这些属性。为了使用 Python 方法将数据框写回 CSV,您需要先使用 r_to_py() 函数将其转换为 Python 对象:

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

    另一种选择是使用原生 R 函数write.csv()

    【讨论】:

      【解决方案2】:

      这就是 R 和 Python 对象模型不同的地方。在 R 中,像 write.csv() 这样的方法是在对象上运行的。但在 Python 中,对象可以具有使用其父对象的可调用属性或属性,例如 DataFrame.to_csv()

      所以只需将方法从 pandas 库调整到数据框本身:

      in.file$to_csv("/path/to/output.csv")
      

      事实上很多I/O methods都是数据框属性:

      in.file$to_excel("/path/to/output.xlsx", excel_writer)
      in.file$to_sql(engine, "table_name")
      in.file$to_hdf("hdf5_store", "table_name")
      
      # OUTPUTS TO STRING
      json_str = in.file$to_json()
      html_str = in.file$to_html()
      

      【讨论】:

        猜你喜欢
        • 2021-11-20
        • 1970-01-01
        • 2018-10-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多