Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing one element with another in Python

I would like to replace inf with 0 in the matrix, P. The desired output is attached.

import numpy as np
P = np.array([-1.54511316e+12,            -inf, -1.54511316e+12,            -inf,
                  -inf,            -inf,            -inf])

The desired output is

array([-1.54511316e+12,            0, -1.54511316e+12,            0,
                  0,            0,            0])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can combine numpy.where and numpy.isfinite:

P2 = np.where(np.isfinite(P), P, 0)

output:

array([-1.54511316e+12,  0.00000000e+00, -1.54511316e+12,  0.00000000e+00,
        0.00000000e+00,  0.00000000e+00,  0.00000000e+00])

Or, for in place modification:

P[~np.isfinite(P)] = 0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading