【问题标题】:Make elements with value division by zero equal to zero in a 2D numpy array使值除以零的元素等于 2D numpy 数组中的零
【发布时间】:2021-11-18 02:52:27
【问题描述】:

我有一个代码sn-p:

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?

【问题讨论】:

    标签: python numpy multidimensional-array division divide-by-zero


    【解决方案1】:

    您可以使用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]])
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-03
        • 1970-01-01
        • 1970-01-01
        • 2021-06-11
        相关资源
        最近更新 更多