我怎么接受"除以零"为零? (Python)的

时间:2017-03-02 18:41:47

标签: python arrays function numpy

所以我有以下代码:

import numpy as np

array1 = np.array([[[[2, 2, 3], [0, 2, 0], [2, 0, 0]],
[[1, 2, 2], [2, 2, 0], [0, 2, 3]],
[[0, 4, 2], [2, 2, 2], [2, 2, 3]]],
[[[2, 3, 0], [3, 2, 0], [2, 0, 3]],
[[0, 2, 2], [2, 2, 0], [2, 2, 3]],
[[1, 0, 2], [2, 2, 2], [2, 2, 0]]],
[[[2, 0, 0], [0, 2, 0], [2, 0, 0]],
[[2, 2, 2], [0, 2, 0], [2, 2, 0]],
[[0, 2, 2], [2, 2, 2], [2, 2, 0]]]])

array2 = np.array([[[[2, 2, 3], [0, 2, 0], [2, 0, 0]],
[[1, 2, 2], [2, 2, 0], [0, 2, 3]],
[[0, 4, 2], [2, 2, 2], [2, 2, 3]]],
[[[2, 3, 0], [3, 2, 0], [2, 0, 3]],
[[0, 2, 2], [2, 10, 0], [2, 2, 3]],
[[1, 0, 2], [2, 2, 2], [2, 2, 0]]],
[[[2, 0, 0], [0, 2, 0], [2, 0, 0]],
[[2, 2, 2], [0, 2, 0], [2, 2, 0]],
[[0, 2, 2], [2, 2, 2], [2, 2, 0]]]])

def calc(x, y):
    result = y/x
    return result

final_result = []
for x, y in zip(array1, array2):
    final_result.append(calc(np.array(x), np.array(y)))

总而言之,我有两个包含一些3D数组的列表,然后我定义了一个函数。最后一部分是我在函数中使用每个3D数组的位置,最终我得到了一些其他3D数组的列表(final_result),其中该函数已用于array1的每个条目, array2

但是,正如您所看到的,最终在函数中提供array1值的x在某些条目中的值为0。是的,从数学角度看,这并不好。但在这种情况下,我真的只需要将零x - 条目的条目设为零。因此,只要发生这种情况,它就不需要运行该函数,但只需跳过它,并将该条目保留为零。

可以这样做吗?

1 个答案:

答案 0 :(得分:3)

此问题已得到解答here。 Numpy有一种特定的方法来捕捉这些错误:

def calc( a, b ):
    """ ignore / 0, div0( [-1, 0, 1], 0 ) -> [0, 0, 0] """
    with np.errstate(divide='ignore', invalid='ignore'):
        c = np.true_divide( a, b )
        c[ ~ np.isfinite( c )] = 0  # -inf inf NaN
    return c
相关问题