Divide one numpy array by another only where both arrays are non-zero

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

What's the easiest, most Pythonic way to divide one numpy array by another (of the same shape, element-wise) only where both arrays are non-zero?

Where either the divisor or dividend is zero, the corresponding element in the output array should be zero. (This is the default output when the divisor is zero, but np.nan is the default output when the dividend is zero.)

回答1:

This still tries to divide by 0, but it gives the correct result:

np.where(b==0, 0, a/b) 

To avoid doing the divide-by-zero, you can do:

m = b!=0 c = np.zeros_like(a) np.place(c, m, a[m]/b[m]) 


回答2:

I would do it in two lines:

z = x/y z[y == 0] = 0 

As you said, if only the element in x is 0, z will already be 0 at that position. So let NumPy handle that, and then fix up the places where y is 0 by using NumPy's boolean indexing.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!