我有一個代碼片段:
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”。
如何使用“嘗試和除外”將所有這些“inf”結果更改為 0?或者是否有更好的方法將所有這些“inf”轉換為 0?
uj5u.com熱心網友回復:
您可以使用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]])
uj5u.com熱心網友回復:
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]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362001.html
