0

Hello I am wondering if I could use something like "try-except" to avoid error warnings and put np.nan in the result array?

for example

import numpy as np
a = np.array([1,1])
b = np.array([1,0])
c = a/b

there will be a "division by zero error" I wish to neglect this error and get c as np.array([1,np.nan])

I know I could use a loop and try-except to achieve this by iterate through all elements in the array. However, is there a more elegant way to do this with out a loop?

If it has to be a loop, what would be the fastest way to do?

Gang
  • 185
  • 1
  • 1
  • 9
  • Does this answer your question? [Replace the zeros in a NumPy integer array with nan](https://stackoverflow.com/questions/27778299/replace-the-zeros-in-a-numpy-integer-array-with-nan) – SKPS Feb 10 '20 at 04:42

1 Answers1

0
In [219]: a = np.array([1,1]) 
     ...: b = np.array([1,0]) 
     ...: c = a/b                                                                              
/usr/local/bin/ipython3:3: RuntimeWarning: divide by zero encountered in true_divide
  # -*- coding: utf-8 -*-
In [220]: c                                                                                    
Out[220]: array([ 1., inf])

Replace the / with divide. As a ufunc it accepts where and out parameters, which work together to skip the 0's and place a nan instead:

In [224]: np.divide(a,b, where=(b!=0), out=np.full(a.shape,np.nan))                            
Out[224]: array([ 1., nan])

It is also possible to suppress the warning, but that doesn't replace the inf with nan. This ufunc code is the simplest way to do both.

Applying a function across a numpy array gives different answers in different runs

hpaulj
  • 221,503
  • 14
  • 230
  • 353