Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppress warnings for python-xarray

I'm running the following code

positive_values = values.where(values > 0)  

In this example values may contain nan elements. I believe that for this reason, I'm getting the following runtime warning:

RuntimeWarning: invalid value encountered in greater_equal if not reflexive  

Does xarray have methods of surpressing these warnings?

like image 243
Conic Avatar asked Feb 06 '23 13:02

Conic


2 Answers

The warnings module provides the functionality you are looking for.

To suppress all warnings do (see John Coleman's answer for why this is not good practice):

import warnings
warnings.simplefilter("ignore") 
# warnings.simplefilter("ignore", category=RuntimeWarning) # for RuntimeWarning only

To make the suppression temporary do it inside the warnings.catch_warnings() context manager:

import warnings

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    positive_values = values.where(values > 0)  

The context manager saves the original warning settings prior to entering the context and then sets them back when exiting the context.

like image 141
Steven Rumbalski Avatar answered Feb 08 '23 14:02

Steven Rumbalski


As a general rule of thumb, warnings should be heeded rather than suppressed. Either you know what causes the warning or you don't. If you know what causes the warning, there is usually a simple workaround. If you don't know what causes the warning, there is likely a bug. In this case, you can use the short-circuiting nature of & as follows:

positive_values = values.where(values.notnull() & values > 0)
like image 39
John Coleman Avatar answered Feb 08 '23 15:02

John Coleman