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

前端 未结 2 1558
醉话见心
醉话见心 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:02

    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.

提交回复
热议问题