繁体   English   中英

如何使用 Rmarkdown 中的 Reticulate 将 Pandas DataFrame 转换为 R DataFrame

[英]How to Convert Pandas DataFrames to R Dataframes using Reticulate in Rmarkdown

我使用 Rmarkdown 和网状 package 将 python 和 R 编织在一起。 但是,将 Pandas DataFrame 转换为 R Dataframes 的过程似乎并不一致。

这是一个可重现的例子:

---
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{python}
import pandas as pd
df = pd.DataFrame({'a':4, 'b':5, 'c':9}, index=[0])
print(df)
```

```{r}
library(reticulate)
df2 <- reticulate::py$df
print(df2)
print(reticulate::py$df)
```

预期结果:
我希望 dataframe(3 次)的粗略呈现如下:

##    a  b  c
## 0  4  5  9

##    a  b  c
## 0  4  5  9

##    a  b  c
## 0  4  5  9

实际结果:

import pandas as pd
df = pd.DataFrame({'a':4, 'b':5, 'c':9}, index=[0])
print(df)
##    a  b  c
## 0  4  5  9
library(reticulate)
df2 <- reticulate::py$df
print(df2)
##                                   a                                 b
## 1 <environment: 0x000000001dddb808> <environment: 0x000000001decdc58>
##                                   c
## 1 <environment: 0x000000001e000918>
print(reticulate::py$df)
##                                   a                                 b
## 1 <environment: 0x000000001e807f78> <environment: 0x000000001e8fd480>
##                                   c
## 1 <environment: 0x000000001e9ee608>
```

请注意,dataframe 从 python 正确打印。一旦我们进入 R,就好像 R dataframe object 已损坏。

这是我的 session 信息:

## R version 3.5.2 (2018-12-20)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## Running under: Windows 10 x64 (build 17134)
##  
## Matrix products: default
##  
## locale:
## [1] LC_COLLATE=English_United States.1252 
## [2] LC_CTYPE=English_United States.1252   
## [3] LC_MONETARY=English_United States.1252
## [4] LC_NUMERIC=C                          
## [5] LC_TIME=English_United States.1252    
##  
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
##  
## other attached packages:
## [1] reticulate_1.10.0.9004
##  
## loaded via a namespace (and not attached):
##  [1] Rcpp_1.0.0      lattice_0.20-38 digest_0.6.16   rprojroot_1.3-2
##  [5] grid_3.5.2      jsonlite_1.6    backports_1.1.2 magrittr_1.5   
##  [9] evaluate_0.11   stringi_1.1.7   Matrix_1.2-15   rmarkdown_1.10 
## [13] tools_3.5.2     stringr_1.3.1   yaml_2.2.0      compiler_3.5.2 
## [17] htmltools_0.3.6 knitr_1.20

我能够做到,但功能的顺序对我来说有点不同。 我很早就用其他 R 包加载了网状包。

我在 Python 中完成了绝大多数工作,然后将其转换为 R 以使用 DT 包获取带有 Excel 和 .CSV 导出按钮的数据视图。

output:
    html_document:
    toc: false
    toc_depth: 1
---

```{r, loadPython, echo=F}
library(reticulate)
library(tidyverse)
library(DT)

```


```{python, echo=T}
# working with pandas df objects continues from other work
predictions = ts.make_predictions(model,
                               series + ' SARIMAX',
                               start=len(train),
                               end= len(train) + len(oos_exog)-1,
                               exog_data=oos_exog)

# make the OOS intervals
intervals = ts.get_oos_conf_interval(model=model,
                                     steps_ahead=short_horizon,
                                     exog_data = oos_exog)
# this is raw output                                     
print(intervals)
```


```{r, echo=T}
# convert the pandas df object to R DF
r_df <- reticulate::py$intervals


# make a function to make fancy tables in R Markdown using DT package
makeTable <- function(df, end_col){
    datatable(df, extensions = 'Buttons',
              options = list(dom = 'Bfrtip',
                                 buttons = list("excel", "csv")
    )) %>% 
        formatRound(columns = c(1:end_col), digits = 0) 
}
r_df

# output the table
makeTable(r_df, end_col=4)
```

在使用网状结构从 R 读取 python pandas 数据帧时,我注意到类似的<environment: ...>列。 例如使用df["x"].str.strip()df.reset_index()转换列在某些情况下有所帮助。

注意:您在问题中提供的 python 和 R 块在我的机器上返回了预期的 output:

> print(reticulate::py$df)
  a b c
0 4 5 9

因此,这些问题可能是由于 pandas 或网状依赖项中的不一致造成的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM