scriptgirl_3000
scriptgirl_3000

Reputation: 193

Interpret division by zero as nan

I'm trying to divide one array by another, say

a = np.array([[2., 2., 2., 2., 2.], [2., 2., 2., 2., 2.]])
b = np.array([[20., 16., 0., 10., nan], [5., 4., nan, 2., 0.]])

np.divide(a,b)

will result in

array([[ 0.1  ,  0.125,    inf,  0.2  ,    nan],
       [ 0.4  ,  0.5  ,    nan,  1.   ,    inf]])

and gives me the error RuntimeWarning: divide by zero encountered in true_divide, which doesn't come as a big surprise.

I tried

try:
    np.divide(a,b)
except ZeroDivisionError:
    value = float('nan')

which didn't work. Also an if-loop wasn't the solution:

if b != 0:
    value = a / b
else:
    value = float('nan')

gives me the error 'The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()'. But using

if np.any(b != 0):

as a first line instead, yields

array([[ 10. ,   8. ,   0. ,   5. ,   nan],
       [  2.5,   2. ,   nan,   1. ,   0. ]])

Same goes for

 if np.all(b != 0):

I do understand that this must be due to the fact that np.any just returns a boolean True or False. Is there no other option as to replace inf-values that come up with

np.divide(a,b)

and accept the RuntimeWarning?

Upvotes: 1

Views: 2636

Answers (1)

jpp
jpp

Reputation: 164613

You can use numpy.isinf to replace inf and -inf values with np.nan:

c = np.divide(a,b)
c[np.isinf(c)] = np.nan

print(c)

[[ 0.1    0.125    nan  0.2      nan]
 [ 0.4    0.5      nan  1.       nan]]

Upvotes: 1

Related Questions