简体   繁体   中英

Numpy conditional arithmetic operations on two arrays

Still trying to earn my numpy stripes: I want to perform an arithmetic operation on two numpy arrays, which is simple enough:

return 0.5 * np.sum(((array1 - array2) ** 2) / (array1 + array2))

Problem is, I need to be able to specify the condition that, if both arrays are element-wise 0 at the same element i , don't perform the operation at all--would be great just to return 0 on this one--so as not to divide by 0.

However, I have no idea how to specify this condition without resorting to the dreaded nested for-loop. Thank you in advance for your assistance.

Edit : Would also be ideal not to have to resort to a pseudocount of +1.

return numpy.select([array1 == array2, array1 != array2], [0.5 * np.sum(((array1 - array2) ** 2) / (array1 + array2)), 0])

应该可以解决问题... numpy.where也可以使用。

Just replace np.sum() by np.nansum() :

return 0.5 * np.nansum(((array1 - array2) ** 2) / (array1 + array2))

np.nansum() treats nan s as zero.

You could also try post-applying numpy.nan_to_num :

http://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html

although I found that when I have a divide by zero in your code, it gives a warning, but fills that element with zero (when doing integer math) and NaN when using floats.

If you want to skip the sum when you have a divide by zero, you could also just do the calculation and then test for the NaN before returning:

xx = np.sum(((array1 - array2) ** 2) / (array1 + array2))
if np.isnan(xx):
    return 0
else:
    return xx 

Edit: To silence warnings you could try messing around with numpy.seterr :

http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM