Search code examples
pythonrr-markdownreticulate

Suppress warnings when using a python chunk inside an Rmd file


I am trying to hide some python warnings when knitting an Rmd file. The usual chunk setup "warning=F, message=F" doesn't seem to work for python chunks.

Example of Rmd file with a python chunk that, purposefully, generates warnings:

---
title: "**warnings test**"
output: pdf_document
---


```{python, echo=F, warning=F, message=F}
import pandas as pd
d = {'col1': [1, 1, 2, 2], 'col2': [0, 0, 1, 1]}
df = pd.DataFrame(data=d)
df[df.col1==1]['col2']=2
```

Solution

  • You can add warnings.filterwarnings('ignore') to the python chunk:

    ```{python, echo=F, warning=F, message=F}
    import warnings
    warnings.filterwarnings('ignore')
    import pandas as pd
    d = {'col1': [1, 1, 2, 2], 'col2': [0, 0, 1, 1]}
    df = pd.DataFrame(data=d)
    df[df.col1==1]['col2']=2
    ```