Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove nan and inf values from a numpy matrix?

Here is my code

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)`

I am getting Nan and inf values.i tried to remove differently means once i removed Nan and then i removed Inf values and replace them with 0.But i need to replace them together!Is there any way to replace them together ?

like image 826
Md. Mahedi Hasan Riday Avatar asked Sep 22 '18 16:09

Md. Mahedi Hasan Riday


1 Answers

You can just replace NaN and infinite values with the following mask:

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.        ]])
like image 187
sacuL Avatar answered Oct 18 '22 22:10

sacuL