10

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 ?

1
  • "But i need to replace them together!I" Why? Commented Sep 22, 2018 at 16:05

3 Answers 3

12

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.        ]])
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need the isnan, isfinite checks for both: "Test element-wise for finiteness (not infinity or not Not a Number)."
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)

Comments

3

If you don't want to modify the array in place, you can make use of the np.ma library, and create a masked array:

np.ma.masked_array(output, ~np.isfinite(output)).filled(0)

array([[1.        , 0.5       , 1.        , 1.        , 0.        ,
        1.        ],
       [1.        , 1.        , 0.5       , 1.        , 0.46524064,
        1.        ],
       [1.        , 1.        , 1.        , 0.        , 1.        ,
        1.        ]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.