Search code examples
pythonnumpydivideoperation

RuntimeWarning: divide by zero encountered in divide


I'm asking a question about this error : RuntimeWarning: divide by zero encountered in divide

For example, I have two 2D arrays. The first one contains lot of data (array_1), and the second one owns binary data (0 or 1) as a mask (mask_array).

I would like make this operation :

result = array_1 / mask_array

Obviously, I will get this RuntimeWarning error. So my question is : Is it possible to write something like this : If I divide by zero, write 0 as result ?

I suppose that I will get a NaN if I divide by 0 ?

So how I can make the operation and replace the result by zero each time I will get the error ?

Thank you to your help !


Solution

  • It seems like you just want to set all elements to zero where the mask_array is 0.

    You can just set all of these elements to zero by using:

    result = array_1.copy()
    result[mask_array == 0] = 0  # Indexes all elements that are zero and sets them to zero.
    

    or you could also use numpy.ma.MaskedArray:

    result = np.ma.array(array1.copy(), mask=mask_array)
    

    and then do operations with it.

    Also the comment by @schwobaseggl could be very helpful because you probably want multiplication instead of division:

    array1 = np.array([1, 2, 3, 4])
    mask = np.array([1, 0, 1, 0])
    array1 * mask
    # gives: array([1, 0, 3, 0])