如何从numpy矩阵中删除nan和inf值?

Md.*_*day 5 python numpy matrix

这是我的代码

import numpy as np
cv = [[1,3,4,56,0,345],[2,3,2,56,87,255],[234,45,35,76,12,87]]
cv2 = [[1,6,4,56,0,345],[2,3,4,56,187,255],[234,45,35,0,12,87]]

output = np.true_divide(cv,cv2,where=(cv!=0) | (cv2!=0))
print(output)`
Run Code Online (Sandbox Code Playgroud)

我正在获取Nan和inf值。我试图以不同的方式删除意味着一旦我删除了Nan然后又删除了Inf值并将其替换为0.但是我需要一起替换它们!有什么办法可以一起替换它们?

sac*_*cuL 6

您可以NaN使用以下掩码替换和无限值:

output[~np.isfinite(output)] = 0

>>> output
array([[1.        , 0.5       , 1.        , 1.        , 0.        ,
        1.        ],
       [1.        , 1.        , 0.5       , 1.        , 0.46524064,
        1.        ],
       [1.        , 1.        , 1.        , 0.        , 1.        ,
        1.        ]])
Run Code Online (Sandbox Code Playgroud)

  • 您不需要`isnan`,`isfinite`都检查:[[对元素进行有限性测试(不是无穷或不是数字)。“](https://docs.scipy.org/doc/ numpy-1.13.0 / reference / generation / numpy.isfinite.html) (2认同)

apa*_*kin 6

There is a special function just for that:

numpy.nan_to_num(x_arr, copy=False, nan=0.0, posinf=0.0, neginf=0.0)
Run Code Online (Sandbox Code Playgroud)