Search code examples
pythonarraysnumpydivide-by-zero

Division by zero in numpy (sub)arrays


I have three arrays that are processed with a mathematical function to get a final result array. Some of the arrays contain NaNs and some contain 0. However a division by zero logically raise a Warning, a calculation with NaN gives NaN. So I'd like to do certain operations on certain parts of the arrays where zeros are involved:

r=numpy.array([3,3,3])
k=numpy.array([numpy.nan,0,numpy.nan])
n=numpy.array([numpy.nan,0,0])
1.0*n*numpy.exp(r*(1-(n/k)))

e.g. in cases where k == 0, I'd like to get as a result 0. In all other cases I'd to calculate the function above. So what is the way to do such calculations on parts of the array (via indexing) to get a final single result array?


Solution

  • import numpy
    r=numpy.array([3,3,3])
    k=numpy.array([numpy.nan,0,numpy.nan])
    n=numpy.array([numpy.nan,0,0])
    indxZeros=numpy.where(k==0)
    indxNonZeros=numpy.where(k!=0)
    d=numpy.empty(k.shape)
    d[indxZeros]=0
    d[indxNonZeros]=n[indxNonZeros]/k[indxNonZeros]
    print d