我有一个代码片段:
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?
2条答案
按热度按时间zpjtge221#
您可以使用
numpy.where
来选择要保留除法结果或原始值的值:输出:
或者,使用
numpy.divide
的where
参数来保留原始值:请注意,行为不太明显,您可能需要检查两个值是否都为非空:
cgfeq70w2#
0/0
可以通过将invalid='ignore'
添加到numpy.errstate()
来处理,引入numpy.nan_to_num()
将np.nan
转换为0
。输出