开发者

Numpy conditional arithmetic operations on two arrays

开发者 https://www.devze.com 2023-02-17 05:37 出处:网络
Still trying to earn my numpy stripes: I want to perform an arithmetic operation on two numpy arrays, which is simple enough:

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.


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

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

np.nansum() treats nans as zero.


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

should do the trick... numpy.where might also be used.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消