仅在两个数组都不为零的情况下,将一个numpy数组除以另一个 [英] Divide one numpy array by another only where both arrays are non-zero

查看:82
本文介绍了仅在两个数组都不为零的情况下,将一个numpy数组除以另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅当两个数组都不为零时,将一个numpy数组除以另一个(形状相同,在元素上相同)的最简单,最Python化的方法是什么?

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?

如果除数或除数为零,则输出数组中的相应元素应为零. (这是除数为零时的默认输出,但np.nan是除数为零时的默认输出.)

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.)

推荐答案

这仍然尝试除以0,但是给出正确的结果:

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])

这篇关于仅在两个数组都不为零的情况下,将一个numpy数组除以另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆