Skip to main content
 首页 » 编程设计

python之如何将 Python Pandas Dataframe 转换为 R data.frame

2025年02月15日7cmt

我正在使用 R 包 PythonInR,并想使用函数 pyGet() 将 pandas 数据帧转换为 R 数据帧,但出现以下错误:

Error in as.data.frame.default(xi, optional = TRUE, stringsAsFactors = stringsAsFactors) : cannot coerce class ""PythonObject"" to a data.frame

text.csv 文件只包含两列,name(string) 和 value(int)。 代码如下:

library(PythonInR)  
pyConnect()  
pyIsConnected()  
pyVersion() 
pyOptions("usePandas", TRUE)  
pyImport("pandas", as="pd")  
test_code <-'py_df = pd.read_csv("test.csv")'  
pyExec(code = test_code)  
r_df <- pyGet("py_df") 

代码的输出是:

library(PythonInR) 
pyConnect() 
R is already connected to Python! 
pyIsConnected() 
[1] TRUE 
pyVersion() 
[1] "3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]" 
pyOptions("usePandas", TRUE) 
pyImport("pandas", as="pd") 
test_code <- 'py_df = pd.read_csv("test.csv")' 
pyExec(code = test_code) 
r_df <- pyGet("py_df") 

Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : cannot coerce class ""PythonObject"" to a data.frame

谁能帮助建议如何使用 PythonInR 将 Pandas 数据帧转换为 R data.frame?

请您参考如下方法:

你可以使用 json。 pandas dataframe 有一个 to_json 方法,您可以使用 rjson R 包使用 fromJSON 读取 json 字符串。

您还可以找到 this和 this有趣的。计划很快提交给 CRAN,但我需要做更多的测试。