简体   繁体   English

两个数组上的Numpy条件算术运算

[英]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: 仍然试图赚取numpy条纹:我想对两个numpy数组执行算术运算,这很简单:

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. 问题是,我需要能够指定以下条件:如果两个数组在同一元素i都是按元素方式为0,则根本不执行该操作-只需在该元素上返回0就好了-以免被0除。

However, I have no idea how to specify this condition without resorting to the dreaded nested for-loop. 但是,我不知道如何在不借助可怕的嵌套for循环的情况下指定此条件。 Thank you in advance for your assistance. 预先感谢您的协助。

Edit : Would also be ideal not to have to resort to a pseudocount of +1. 编辑 :也将是理想的,不必诉诸+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() : 只需将np.sum()替换为np.nansum()

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

np.nansum() treats nan s as zero. np.nansum()nan视为零。

You could also try post-applying numpy.nan_to_num : 您也可以尝试后期应用numpy.nan_to_num

http://docs.scipy.org/doc/numpy/reference/generated/numpy.nan_to_num.html 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. 尽管我发现当您的代码中被零除时,它会发出警告,但使用浮点数时,该元素将填充零(在执行整数数学运算时)和NaN。

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: 如果要在除以零时跳过总和,则还可以进行计算,然后在返回之前测试NaN

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 : 编辑:要使警告静音,您可以尝试与numpy.seterr

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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