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

前端 未结 2 1564
醉话见心
醉话见心 2020-12-21 04: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 d

2条回答
  •  旧巷少年郎
    2020-12-21 05:04

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

提交回复
热议问题