I am doing some simple math recessively in a python script and am getting the follow warning:
"Warning: divide by zero encountered in divide".
To provide some context, I am taking two values and trying to find the percent difference in value (a - b) / a
and if its above a certain range then process it, but sometimes the value of a
or b
is zero.
I want to get rid of this specific warning (at a specific line) but all the information I have found so far seems to show me how to stop all warnings (which I do not want).
When I used to write shell scripts, I could do something like this
code... more code 2 > error.txt even more code
In that example, I would get the warnings for the 'code' and 'even more code' command but not for the second line.
Is this possible?
Use the filterwarnings() Function to Suppress Warnings in Python. The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.
To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings. Show activity on this post. from IPython. display import HTML HTML('''<script> var code_show_err = false; var code_toggle_err = function() { var stderrNodes = document.
When nothing else works: $ pip install shutup . Then at the top of the code import shutup;shutup. please() . This will disable all warnings.
showwarning() This method is used to display the warning to the user.
If Scipy is using the warnings
module, then you can suppress specific warnings. Try this at the beginning of your program:
import warnings warnings.filterwarnings("ignore", message="divide by zero encountered in divide")
If you want this to apply to only one section of code, then use the warnings context manager:
import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", message="divide by zero encountered in divide") # .. your divide-by-zero code ..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With