在2D numpy数组中使值除以零的元素等于零

6qqygrtg  于 2023-04-12  发布在  其他
关注(0)|答案(2)|浏览(118)

我有一个代码片段:

import numpy as np
x1 = [[1,4,2,1],       
      [1,1,4,5],
      [0.5,0.3, 1,6],
      [0.8,0.2,0.7,1]]

x2 = [[7,0,2,3],       
      [8,0,4,5],
      [0.1,0, 2,6],
      [0.1,0,0.16666667,6]]

np.true_divide(x1, x2)

输出为:

array([[0.14285714,        inf, 1.        , 0.33333333],
       [0.125     ,        inf, 1.        , 1.        ],
       [5.        ,        inf, 0.5       , 1.        ],
       [8.        ,        inf, 4.19999992, 0.16666667]])

我知道有些元素会有零除法误差,可以看作是“inf”。
我如何使用'try and except'将所有这些'inf'结果转换为0?或者有更好的方法将所有这些'inf'转换为0?

zpjtge22

zpjtge221#

您可以使用numpy.where来选择要保留除法结果或原始值的值:

import numpy as np
x1 = np.array([[1,4,2,1],       
               [1,1,4,5],
               [0.5,0.3, 1,6],
               [0.8,0.2,0.7,1]])
x2 = np.array([[7,0,2,3],       
               [8,0,4,5],
               [0.1,0, 2,6],
               [0.1,0,0.16666667,6]])

np.where(x2==0, 0, x1/x2)
# or
# np.where(x2==0, x2, np.true_divide(x1, x2))

输出:

array([[0.14285714, 0.        , 1.        , 0.33333333],
       [0.125     , 0.        , 1.        , 1.        ],
       [5.        , 0.        , 0.5       , 1.        ],
       [8.        , 0.        , 4.19999992, 0.16666667]])

或者,使用numpy.dividewhere参数来保留原始值:

np.divide(x1, x2, where=x2!=0)

请注意,行为不太明显,您可能需要检查两个值是否都为非空:

x1 = np.array([2,2,0,0])
x2 = np.array([2,0,2,0])
np.divide(x1, x2, where=(x2!=0)&(x1!=0)).round(10)
# array([1., 0., 0., 0.])
cgfeq70w

cgfeq70w2#

0/0可以通过将invalid='ignore'添加到numpy.errstate()来处理,引入numpy.nan_to_num()np.nan转换为0

with np.errstate(divide='ignore', invalid='ignore'):
    c = np.true_divide(x1,x2)
    c[c == np.inf] = 0
    c = np.nan_to_num(c)
print(c)

输出

[[0.14285714 0.         1.         0.33333333]
 [0.125      0.         1.         1.        ]
 [5.         0.         0.5        1.        ]
 [8.         0.         4.19999992 0.16666667]]

相关问题