pythonrpandasreticulate

How to stop the annoying warnings output by reticulate in R


I am trying to read a pickle data in R, I have following R code:

library(reticulate)
pd <- suppressMessages(import("pandas"))
hubs.data <- suppressWarnings(pd$read_pickle("input.pickle"))

The code is worked well, but its will output a warnning:

sys:1: FutureWarning: pandas.Float64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
sys:1: FutureWarning: pandas.Int64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.
sys:1: FutureWarning: pandas.UInt64Index is deprecated and will be removed from pandas in a future version. Use pandas.Index with the appropriate dtype instead.

This warning will show when exculate any other R code line after this. I want to stop it.

I have tried:

pd <- suppressWarnings(import("pandas"))
# or
pd <- suppressMessages(import("pandas"))

But the suppressWarnings/suppressMessages seem not work


Solution

  • You can control Python warnings within Python / through reticulate; this is basically what reticulate::py_suppress_warnings() does.

    For testings purposes we first set up a reprex to always show warnings, otherwise trigger_warning() would only warn once, during the first occurrence. Then we'll suppress it with warnings$simplefilter("ignore") when calling from R (or with warnings.simplefilter("ignore") from Python).

    Python warning categories and filter actions along with examples can be found from https://docs.python.org/3/library/warnings.html

    library(reticulate)
    # use specific conda env
    # use_condaenv("py311") 
    
    # change Python(!) warning action from `once` to `always` for testing;
    # create a dummy function to trigger FutureWarning
    py_run_string('
    import warnings
    
    warnings.simplefilter("always")
    def trigger_warning():
      warnings.warn("a future warning", FutureWarning)
      return 42
    ')
    
    # triggering a warning:
    py$trigger_warning()
    #> <string>:6: FutureWarning: a future warning
    #> [1] 42
    
    # control Pyhon warnings through reticulate:
    warnings <- import("warnings")
    
    # ignore / suppress:
    warnings$simplefilter("ignore")
    py$trigger_warning()
    #> [1] 42